Search code examples
matlabstructmatlab-deployment

How to change the Value of a struct with a function in Matlab?


s= struct('Hello',0,'World',0);
for i = 1: 5
     s_vec(i) = s;
end

I have definied a struct in Matlab within a script. Now i want to implement a function witch change the Value of the Parameters. For example:

function s_struct = set_s (number, prop , value) 
         s_struct(number).prop = value;

But the function returns a new struct. It does not change my input struct. Where is my mistake?


Solution

  • I'am not sure to totally understand your question, but if you want to update a parameter in a structure, you have to pass the structure to update as argument of your function.

    Moreover, if prop is the parameter, you should use an dynamic allocation using a string in your function :

    function [ s_struct ] = set_s( s_struct, number, prop, value )
        s_struct(number).(prop) = value;
    end
    

    Using it this way :

    s_vec = set_s(s_vec, 2, 'Hello', 5);
    

    It will update the second value to the parameter 'Hello' to 5.