フィルターのクリア

How do I add a value to a field in each element of a struct array?

20 ビュー (過去 30 日間)
Brandon Kuczenski
Brandon Kuczenski 2014 年 4 月 29 日
コメント済み: Image Analyst 2014 年 4 月 29 日
Say I have a struct array with a numeric field:
>> a=struct('bar',{47 52})
I want to increment that field across each element of the array, something like the following:
>> [a.bar] = [a.bar] + 1; % this fails
The nearest I can figure out is the following, which is cumbersome:
>> inc = num2cell([a.bar]+1);
>> [a.bar] = inc{:};
Is there a way to do this without creating an intermediate variable? Thanks in advance.

回答 (1 件)

Image Analyst
Image Analyst 2014 年 4 月 29 日
Well why are you messing around with cell arrays? Why make it way more complicated than it needs to be??? I don't see any reason for a cell array. I think you need to read the FAQ: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F
Try using just regular numerical arrays:
% Create structure.
a=struct('bar',[47 52])
a.bar % Report to command window.
% Add 1
a.bar = a.bar+1
a.bar % Report to command window.
In the command window:
a =
bar: [47 52]
ans =
47 52
a =
bar: [48 53]
ans =
48 53
  2 件のコメント
Brandon Kuczenski
Brandon Kuczenski 2014 年 4 月 29 日
Your 'a' is not a struct array- it is a struct with one field whose contents are an array. In my version, a(1).bar = 47, a(2).bar=52, and a.bar(2) gives an error.
Image Analyst
Image Analyst 2014 年 4 月 29 日
Sorry, I misunderstood. A fast, straightforward and intuitive solution is to simply use a for loop:
for k = 1:length(a)
a(k).bar = a(k).bar+1;
end
Don't believe the hype about a for loop being slow. It's not. Assuming you have less than several million structures in the array, it should be very fast.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by