Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing one element in a vector within a function

I want to change a single element in a vector:

function vecteur_avec_delai=delai(input_vecteur, iteration)
    vecteur_avec_delai(iteration,1) =  input_vecteur(iteration,1);
end

input_vecteur is a vector of size 6001 -by- 1 filled with the same value: 61.46 , and vecteur_avec_delai = ones(6001,1)

I want to change one value of vecteur_avec_delai to 61.46, so to still have a vector of length 6001, filled with ones except one cell with a value equal to 61.46, thus the vecteur_avec_delai(iteration,1) = input_vecteur(iteration,1);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I run :

vecteur_avec_delai=delai(input_vecteur, iteration)

It compiles but gives me for output a vecteur_avec_delai of size (iteration, 1 ) filled with 0s except for the last value equal to 61.46.

When I try this operation "manually" (directly in the MATLAB command window), it works, so why doesn’t it when I go through this function?

>Solution :

You haven’t declared vecteur_avec_delai as input into the function. This boils down to calling A(10,1) = 1 in a clean command window: it creates a 10-by-1 vector with 9 zeros and a 1 at the end. Instead, first declare your array to be ones and then set only this required element:

function vecteur_avec_delai=delai(input_vecteur, iteration)
    vecteur_avec_delai = ones(size(input_vecteur));
    vecteur_avec_delai(iteration,1) =  input_vecteur(iteration,1);
end

Or, given your comment about it working in the command window, simply add vecteur_avec_delai to the inputs of the function (you might want to change the names of the input and output variables to not be the same for clarity). Functions are closed name-spaces, i.e. they have their own "workspace" so to say, and cannot see anything outside of that function, hence the need to declare all inputs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading