フィルターのクリア

How to extract data from strcture ?

2 ビュー (過去 30 日間)
Abdelwahab Fawzy
Abdelwahab Fawzy 2016 年 7 月 16 日
編集済み: per isakson 2016 年 7 月 17 日
if i have a structure of 101 nodes, i want to extract the data of the first 99 nodes only in an array
  1 件のコメント
per isakson
per isakson 2016 年 7 月 16 日
Depends on what you mean by "node"

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

採用された回答

Image Analyst
Image Analyst 2016 年 7 月 16 日
If you have a structure array of more than 100 "elements", then you can extract the first 99 like this:
s99 = s(1:99);
This will extract the first 99 into another variable, s99, and all "fields" of the structure will also be brought along.

その他の回答 (1 件)

per isakson
per isakson 2016 年 7 月 16 日
If you by "node" mean what is called field in Matlab
%%create a stucture with 101 fields
sas = cell2struct( num2cell(1:101) ...
, arrayfun( @(x)sprintf('F%03d',x),(1:101), 'uni',false ) ...
, 2 );
%%extract the data of the first 99 fields
len = 99;
M = nan(1,len);
field_list = fieldnames( sas );
for jj = 1 : len
M(jj) = sas.(field_list{jj});
end
  2 件のコメント
Walter Roberson
Walter Roberson 2016 年 7 月 17 日
Or you could struct2cell(), extract the appropriate components of the cell, and cell2struct() the result.
per isakson
per isakson 2016 年 7 月 17 日
編集済み: per isakson 2016 年 7 月 17 日
Yes, struct2cell provides a more compact code. Try
>> cssm
Elapsed time is 0.000301 seconds.
Elapsed time is 0.000241 seconds.
ans =
1
Elapsed time is 0.000101 seconds.
ans =
1
where
function cssm( )
%%create a stucture with 101 fields
sas = cell2struct( num2cell(1:101) ...
, arrayfun( @(x)sprintf('F%03d',x),(1:101), 'uni',false ) ...
, 2 );
len = 99;
%%use for-loop to extract the data of the first 99 fields
tic
M1 = nan(len,1);
field_list = fieldnames( sas );
for jj = 1 : len
M1(jj) = sas.(field_list{jj});
end
toc
%%use struct2cell and cell2mat to extract the data of the first 99 fields
tic
cac = struct2cell( sas );
M2 = cell2mat( cac(1:len) );
toc
all( M2 == M1 )
%%use struct2cell and cat to extract the data of the first 99 fields
tic
cac = struct2cell( sas );
M3 = cat( 1, cac{1:len} );
toc
all( M3 == M1 )
end

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by