How to create a struct

4 ビュー (過去 30 日間)
Chao Zhang
Chao Zhang 2021 年 6 月 19 日
コメント済み: Chao Zhang 2021 年 6 月 20 日
There is a simple way to create a struct like the following picture, i.e ROCK = struct('ROCK0', value1, 'ROCK44', value2, 'ROCK50',value3, ....)
I was curious, is there any other ways to create a struct like the above, so i use for loop to do it, and the code is:
for m = 1 : size(rock_code,1)%Assign values to the initial cell
row_index = rock(:,col_ind_rk) == rock_code(m);%determine the row index according to the corresponding rock codes
sub_rock{m} = rock(row_index,:);
end
% Create string for each sub_rock
str_rock = cell(1,size(rock_code,1));%create cell to store strings
for kk = 1 : size(rock_code,1)
str_rock{kk} = sprintf('ROCK%d',rock_code(kk));
end
% Assign strings to each sub_rock
%create struct to store string and values
ROCK = struct;
for ii = 1 : size(rock_code,1)
ROCK = struct(str_rock{1,ii},sub_rock{1,ii});
end
But there is only the name and value of the last rock (i.e. ROCK53) in this structure, so, is there any way to achieve this struct like using for loop or other methods, thanks!
  2 件のコメント
Stephen23
Stephen23 2021 年 6 月 19 日
If you have any choice on the data design, then the best solution is to avoid forcing meta-data into fieldnames and simply use to basic arrays:
data = {1x13,2x13,2x13, .. etc}
rock = [ 0, 44, 50,51,52,53]
This makes processing the (meta-)data simpler and more efficient.
Chao Zhang
Chao Zhang 2021 年 6 月 20 日
Thanks!

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

採用された回答

Jonas
Jonas 2021 年 6 月 19 日
編集済み: Jonas 2021 年 6 月 19 日
use
for ii = 1 : size(rock_code,1)
ROCK.(str_rock{ii}) = sub_rock{1,ii};
end
at the end if sub_rock cell entries are the values for the fields

その他の回答 (1 件)

Jan
Jan 2021 年 6 月 19 日
str_rock = sprintfc('ROCK%d', rock_code); % Undocumented
ROCK = cell2struct(str_rock(:), sub_rock(:));
  1 件のコメント
Chao Zhang
Chao Zhang 2021 年 6 月 20 日
Thank you

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

カテゴリ

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