I have a matlab function that takes a struct array in my workspace as an input.The struct has fields a and b. I want to add another field c in the struct. Please how fdo I do this.

Antworten (1)

madhan ravi
madhan ravi am 15 Mär. 2019

0 Stimmen

yourstruct.c=...;
% doc setfield()

7 Kommentare

Daniel Boateng
Daniel Boateng am 15 Mär. 2019
function [b]= Testing2(old)
b= old.c;
end
I tried but i get this error
Reference to non-existent field 'c'.
Error in Testing2 (line 2)
b= old.c;
madhan ravi
madhan ravi am 15 Mär. 2019
Bearbeitet: madhan ravi am 15 Mär. 2019
old.c=...; the values that you want to assign to the field c
Thanks for your comment. I tried it but in my output i still have the old subfield but not the new one. Is there something I am missing?
Thanks
function [b]= Testing2(old)
b= old;
old.c= 'blue';
end
Yes, you didn't call the function:
new = Testing2(old) % function call
function new = Testing2(old) % function definition
new = old;
new.c = 'blue';
end
Is there something I am missing?
Yes, of course. Your code
function b = Testing2(old) %note that old is a copy of the variable that was passed as input to the function
b = old; %so b is now a copy of old, completely independent of old
old.c = 'blue'; %modify old. DOES NOT modify b
end %function ends, returns b, discards the modified old since it's not an output.
The fix is to modify b not old:
function b = Testing2(old)
b = old;
b.c = 'blue';
end
or even simpler
function old = Testing2(old)
old.c = 'blue';
end
The latter code may be more efficient under some circumstances as well.
Daniel Boateng
Daniel Boateng am 15 Mär. 2019
Thanks bro. It works perfectly
madhan ravi
madhan ravi am 15 Mär. 2019
Thank you Guillaume for the explanation.

Melden Sie sich an, um zu kommentieren.

Kategorien

Tags

Gefragt:

am 15 Mär. 2019

Kommentiert:

am 15 Mär. 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by