Reputation: 25
After years of anonymity I've just created my account to ask a question which has been bugging me for a while and I just can't seem to find an answer. I really, really tried! Here it goes:
If you have the matlab structure array:
something(1).toSay = 'qwe';
something(2).toSay = 'asd';
something(3).toSay = 'zxc';
Is there any way to vectorize the reassignment of these 3 entries of the field toSay
?
Like
something = magicFunction(something, [1:3], 'toSay', {'newString1','newString2','newString3'})
final results being:
something(2).toSay >> 'newString2'
I've tried something along with the setfield
function, but couldn't make it work. All I'm trying to do with this question is avoid a for-loop.
Question 2: Would it make a difference if it was a cell array of structures and not a structure array?
Upvotes: 2
Views: 51
Reputation: 65430
You can place your replacement strings within a cell array and then use {:}
indexing to create a comma separated list on the right-hand side of the assignment. On the left-hand side, something(1:3).toSay
already creates a comma separated list so we can enclose it in []
to assign the values on the right to their corresponding fields on the left.
newvalues = {'newString1', 'newString2', 'newString3'};
[something(1:3).toSay] = newvalues{:};
See: Assigning output from a comma separated list and Assigning to a comma separated list
With respect to your second question, making it a cell array of structs will require an additional step as you can't create a comma separated list directly when the structs are within a cell array. You'd have to first convert them to a struct array
sarray = [something{1:3}];
[sarray.toSay] = newValues{:};
something(1:3) = num2cell(sarray);
Upvotes: 1