Suppose I have a struct array arr
, where each element has a bunch of fields, including one called val
. I'd like to increment each element's val
field by some constant amount, like so:
for i = 1:length(arr)
arr(i).val = arr(i).val + 3;
end
This obviously works, but I feel there should be a way to do this in just one line of code (and no for loop). The best I've come up with is two lines and requires a temp variable:
newVals = num2cell([arr.val] + 3);
[arr.val] = deal(newVals{:});
Any ideas? Thanks.
deal
. I didn't know aboutsetfield
, so that appears to do it in one line, but as you say, this is certainly worse than the for-loop solution. As for indexing like that, I looked into it a while ago; basically, Mathworks claims that supporting anything like that will force compatibility-breaking changes to the parser. Which is a shame, as it bugs me almost every time I write any Matlab code. – Nomi