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

孤街浪徒 提交于 2021-02-05 11:13:27

问题


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?


回答1:


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.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/46805628/how-to-change-the-value-of-a-struct-with-a-function-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!