How to create a structure of matrices within a loop

6 ビュー (過去 30 日間)
Joanna Przeworska
Joanna Przeworska 2021 年 3 月 2 日
コメント済み: Joanna Przeworska 2021 年 3 月 3 日
Dear all,
Using the following code, I would like to create a structure containing 3 matrices that are the result of a loop. I want these matrices to be named within this structure, e.g. 'A', 'B' and 'C'. What should I improve in my code?
for s0 = 1:3
matrixOfCodes = cell(size(matrixOfNames,2), length(codePart1));
for s1 = 1:size(matrixOfNames,2)
for s2 = 1:length(codePart1)
fullPath = strcat(codePart1{s2}, matrixOfNames{s0,s1}, codePart2{s2});
matrixOfCodes{s1, s2} = fullPath;
end
end
m{s0} = matrixOfCodes;
matrixOfCodes = [];
end

採用された回答

Stephen23
Stephen23 2021 年 3 月 2 日
編集済み: Stephen23 2021 年 3 月 2 日
C = {'A','B','C'};
S = struct();
for k = 1:numel(C)
S.(C{k}) = whatever
end
Note that accessing data like this may be less convenient than simply using the existing arrays and indexing.

その他の回答 (1 件)

Joanna Przeworska
Joanna Przeworska 2021 年 3 月 2 日
Dear Stephen,
Thank you for your response, however when I implement your idea I get an error: 'Argument to dynamic structure reference must evaluate to a valid field name'. My code now look like the one below:
database = {'A','B','C'};
m = struct();
for s0 = 1:numel(database)
matrixOfCodes = cell(size(matrixOfNames,2), length(codePart1));
for s1 = 1:size(matrixOfNames,2)
for s2 = 1:length(codePart1)
fullPath = strcat(codePart1{s2}, matrixOfNames{s0,s1}, codePart2{s2});
matrixOfCodes{s1, s2} = fullPath;
end
end
m.(database) = matrixOfCodes;
end
  2 件のコメント
Stephen23
Stephen23 2021 年 3 月 2 日
@Joanna Przeworska: I fixed my answer. You will need this:
m.(database{s0}) = ..
% ^^^^ index
Joanna Przeworska
Joanna Przeworska 2021 年 3 月 3 日
Dear Stephen,
The code works now exactly as I expected. Thank you very much!
Kind regards,
Joanna

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

カテゴリ

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