フィルターのクリア

Copy of one field of a structured array

6 ビュー (過去 30 日間)
John Petersen
John Petersen 2013 年 3 月 12 日
Is there a way to make a copy of one field of a structured array without doing a loop? I have tried but it just results in the first element.
Creation of sample structure
for i=1:5
A(i).A = i;
A(i).B = i+10;
end
>>C = A.B
C =
11
Likewise
>> C = A(1:3).B
C =
11
instead of C(1).B = 11, C(2).B = 12, and C(3).B = 13 like I want.

採用された回答

per isakson
per isakson 2013 年 3 月 12 日
編集済み: per isakson 2013 年 3 月 12 日
One way to do it:
>> C = cell2struct( num2cell([A.B]), {'B'} )
C =
5x1 struct array with fields:
B
>> C(1).B
ans =
11
>> C(2).B
ans =
12
another
>> C = struct( 'B', num2cell([A.B]) )
C =
1x5 struct array with fields:
B
>> C(1).B
ans =
11
>> C(2).B
ans =
12
>>
  1 件のコメント
John Petersen
John Petersen 2013 年 3 月 12 日
Thanks per! You've made the 1000 milestone.

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

その他の回答 (2 件)

the cyclist
the cyclist 2013 年 3 月 12 日
編集済み: the cyclist 2013 年 3 月 12 日
Yet another way:
[C(1:numel(A)).B] = A.B;
Note that this method will not overwrite other fields of C, if they exist. Some of the methods in other answers will, so be cautious!
  2 件のコメント
per isakson
per isakson 2013 年 3 月 12 日
編集済み: per isakson 2013 年 3 月 12 日
The two functions, struct and cell2struct, create a new struct and overwrite an existing C.
I'll try to remember that numel(A) in the rhs-expression creates a new struct if C does not exist. And I'll reread the entry on deal in the documentation.
John Petersen
John Petersen 2013 年 3 月 13 日
Thanks to the cyclist. This is actually what I was looking for!

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


Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 12 日
C=struct('B',{A.B})

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by