Use text strings in a cell array in a 'for loop' and also use that text string to name the output

조회 수: 3 (최근 30일)
I have a list of 9 site names in a column array "sitearray". Those same 9 names appear in a data structure with subfolders, e.g. 9 matrices indexed by 'Data."sitename".matrix'. I would like to perform the same operation on each of the 9 matrices in a for loop e.g. extract the first value of the matrix, and save the output retaining each sitename. I cannot figure out how to link the text of the sitename to the counter variable in the code.
%(Below doesn't work)
for i=1:length(sitearray)
Output_sitearray(i) = Data.sitename(i).matrix(:,[1]);
end
  댓글 수: 3
Matt Weber
Matt Weber 2022년 6월 30일
Structfun might help but I can't figure out how to use this on all matrixes that are the 3rd level deep in the struct variable. If the data is organized as "Data.sitename.matrix" with 9 sitenames, what Structfun syntax would I use to get an output with the operation done on the "matrix" under each of the 9 sitenames?
Stephen23
Stephen23 2022년 6월 30일
S.hello.matrix = [1,2,3];
S.world.matrix = [4,5,6];
F = @(s)s.matrix(1);
V = structfun(F,S)
V = 2×1
1 4

댓글을 달려면 로그인하십시오.

채택된 답변

Keshav
Keshav 2022년 6월 30일
you can use the below code.
for i=1:length(sitearray)
Output_sitearray(i) = Data.(sitename(i)).matrix(:,[1]);
end
  댓글 수: 13
Stephen23
Stephen23 2022년 7월 1일
"Would you consider writing some code that demonstrates an efficient way to get three separate output matrices?"
M_hello = ..
M_world = ..
M_other = ..
"Or if this isn't possible without manually retyping each site name into a matrix in a separate line of code..."
I already wrote that it is certainly possible if you want to force yourself into writing slow, complex, inefficient, obfuscated, insecure, buggy code that is difficult to debug.
"To me manually retyping each site name seems potentially buggy."
Yes, probably best avoided.
Best solution: store (meta-)data as data (i.e. in a variable, not in its name). Much simpler to work with.
Question: what are you going to do with your data? How do you wish to process it?
Matt Weber
Matt Weber 2022년 7월 1일
I will try that. Thanks. Keshav, thanks for taking the time to write code specific to the example that stores in a struct, that might work for me.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by