Home > Software engineering >  Changing one element in a vector within a function
Changing one element in a vector within a function

Time:03-21

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);

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?

CodePudding user response:

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.

  • Related