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

前端 未结 3 428
夕颜
夕颜 2021-01-28 09:37
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 f

相关标签:
3条回答
  • 2021-01-28 09:44

    Although I think Romain's answer is better practice, you can modify parameters without passing them in and out of a function if you use Nested Functions.

    However, I do not like to use them because in complicated large functions it can be quite confusing trying to follow where things are being set and modified.

    That being said here is an example of using a nested function to do what you want.

    function nestedTest()
    %Define your struct
    s= struct('Hello',0,'World',0);
    for i = 1: 5
        s_vec(i) = s;
    end
    disp('Pre-Nested Call')
    disp(s_vec(1))
    set_s(1, 'Hello' , 1);%Set the first element of s_vec without passing it in.
    disp('Post-Nested Call')
    disp(s_vec(1))
    
        function set_s (number, prop , value)
            % Nested can modify vars defined in parent
            s_vec(number).(prop) = value;
        end
    end
    

    Output:

    Pre-Nested Call
        Hello: 0
        World: 0
    
    Post-Nested Call
        Hello: 1
        World: 0
    
    0 讨论(0)
  • 2021-01-28 09:56

    If you want changing data outside your function (aka side effects) use classes instead of structures. Class must be a handle.

    classdef MutableStruct < handle
        properties
            field1;
            field2;
        end
        methods
            function this = MutableStruct(val1, val2)
                this.field1 = val1;
                this.field2 = val2;
            end
        end
    end
    

    There is more information about correct initialization of object arrays: MATLAB: Construct Object Arrays

    0 讨论(0)
  • 2021-01-28 10:00

    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.

    0 讨论(0)
提交回复
热议问题