필터 지우기
필터 지우기

How do I name this variable dynamically?

조회 수: 3 (최근 30일)
Ulrik William Nash
Ulrik William Nash 2016년 9월 12일
편집: Stephen23 2019년 6월 19일
I am trying to fetch a series of simulation runs from a computer, and the following works just fine:
dataset = j1.fetchOutputs{:};
However, I have more than simply j1. I have j1 to ji. So, I thought looping through 1:i using the following line would work, but it doesn't:
batch = sprintf('j%d' ,i)
and then
dataset = batch.fetchOutputs{:};
I get the error:
"Struct contents reference from a non-struct array object". Can someone help me out here?

답변 (2개)

Stephen23
Stephen23 2016년 9월 12일
편집: Stephen23 2019년 6월 19일

Henry Giddens
Henry Giddens 2016년 9월 12일
In your example above, the variable "batch" is a string. You cant reference object properties or methods, or structure fields from a string, which is what the error message is telling you.
In answer to your question for dynamically addressing variable names, you can use 'eval'
batch = eval(sprintf('j%d' ,i));
dataset = batch.fetchOutputs
% or
% dataset = eval(sprintf('j%d.fetchOutputs{:});
A better way i guess would be to store all the variables "j1" to "ji" as inputs to an array when they are created, rather than as seperate variables. Then you would just need to reference each entry in the array and avoid using eval.
  댓글 수: 2
Stephen23
Stephen23 2016년 9월 12일
Let me quote Steve Lord, who works for TMW (the company that make MATLAB):
I know, beginners always think that magically making variables pop into existence is a great idea. It isn't. It is slow and buggy, and those beginners should take the time to learn from Steve Lord and other MATLAB experts who show much faster and more efficient ways to write code.
Henry Giddens
Henry Giddens 2016년 9월 12일
편집: Henry Giddens 2016년 9월 12일
Just to say that I agree, and don't ever use it myself (Don't really know why I suggested it...). Thanks Stephen for giving a good explanation as to why its a bad idea!

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by