Use Value of String Array to name a variable

조회 수: 13 (최근 30일)
Victor Mas
Victor Mas 2020년 12월 2일
편집: Stephen23 2025년 8월 5일
Hello,
I'm trying to combine results of multiple files into one struct.
Said struct should be named the following name:
result.[FileName1].Result1ofFile1
result.[FileName1].Result2ofFile1
result.[FileName2].Result1ofFile2
...
result.[FileNameX].ResultYofFileX
I save the file names in an String array. Thus
FileName(1) = "abc1"
FileName(2) = "abc2"
...
and so on.
Unfortunately I can't figure out how to make it work.
How can I use the String stored in an array as a variable name?
At the end it should look like this, without the need of typing in the abc-Names myself:
result.abc1.Result1ofFile1
result.abc2.Result1ofFile2
  댓글 수: 1
Stephen23
Stephen23 2020년 12월 2일
편집: Stephen23 2025년 8월 5일
"Use Value of String Array to name a variable"
Your question shows that you actually want to name a structure field, not a variable.
One answer to your question would be to use dynamic fieldnames:
But as Ameer Hamza wrote, a much better approach would be to store the filename as data in its own field.

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

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 12월 2일
First, I must say that this does not seem to be a good idea. It is better to store filenames as a separate field and create an array of the struct. For your case, something like this might be better.
result = struct('data', {}, 'filename', {});
result(1).data = Result1ofFile1;
result(1).filename = FileName(1);
result(2).data = Result1ofFile2;
result(2).filename = FileName(2);
For your current question, you can try something like this
FileName(1) = "abc1";
FileName(2) = "abc2";
C = cell(1, 2*numel(FileName));
C(1:2:end) = num2cell(FileName);
result = struct(C{:});

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by