Hi! I would like to create a conditional statement where the parameters of my if statement is changing. Is it possible to vary the parameters in the if statement?
Here is an example:
x10=1;
i=10;
word='x';
if ('%s%d~=1',word,i)
v='not working'
end
I tried this one but it is not working, any suggestion on how to make it work?

 채택된 답변

the cyclist
the cyclist 2014년 3월 9일

1 개 추천

Here is the closest I can get to the code that I think you wanted:
x10=1;
i=10;
word='x';
% Create a "pass/fail" variable that will be tested.
eval(sprintf('PF = %s%d~=1;',word,i))
% Do the test
if PF
v = 'not working'
end

댓글 수: 3

Guessing you can avoid some of this awkward code by using cell array variables such as
x{10}
rather than names like x10, but maybe not, because it looks like even the text of the variable name can vary.
ericson
ericson 2014년 3월 9일
Yes, both the variable and digit vary
Is there an alternative way wherein I don't need to store it to another variable? I'm using this code for my GUI wherein I will need that code to compare to almost 3000 variables. If I add more variables, it will make the real time clock in my GUI hang.
x10=1;
i=10;
word='x';
% Create a "pass/fail" variable that will be tested.
eval(sprintf('if %s%d~=1, v = ''not working''; disp(v); end ',word,i))
If you don't actually need to display the 'not working' text, then you can get rid of the
disp(v)
statement inside the eval() statement.

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

추가 답변 (1개)

Mischa Kim
Mischa Kim 2014년 3월 9일
편집: Mischa Kim 2014년 3월 9일

0 개 추천

Something like:
mynum = 2; % change to mynum = 1
x10 = 1;
word = 'x';
i = 10;
if (eval(genvarname(strcat(word,num2str(i)))) == mynum)
fprintf('x10 is %d\n', mynum);
else
fprintf('x10 is not %d\n', mynum);
end

댓글 수: 1

ericson
ericson 2014년 3월 9일
Is there an alternative way wherein I don't need to store it to another variable? I'm using this code for my GUI wherein I will need that code to compare to almost 3000 variables. If I add more variables, it will make the real time clock in my GUI hang.

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

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

질문:

2014년 3월 9일

편집:

2014년 3월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by