MATLAB Select variable automatically in matlab

  • Thread starter Thread starter mathia
  • Start date Start date
  • Tags Tags
    Matlab Variable
AI Thread Summary
The discussion revolves around an issue with selecting variables automatically in MATLAB using a loop and the `exist` function. The user encounters an error stating that the first input to `exist` must be a string. Suggestions include focusing on getting the `eval` function to work independently before integrating it into the loop. It is noted that `eval` should return a valid MATLAB statement, and there may be confusion about its output. The error arises because `exist` requires a string input, not the output from `eval`. A recommendation is made to use the `strcat` function for string concatenation instead of relying on `eval`, as it may resolve the issue more effectively.
mathia
Messages
15
Reaction score
0
Hi,
I want to select my variable automatically in MATLAB so I used the following commands: (may variable for example are: Mpoint1,Mpoint5,Mpoint14,...)

for i=1:50
if exist (eval(['Mpoint' num2str(i)]));
statements
else
continue
end
end
but it gave me the following error:

Error using exist
The first input to exist must be a string.

Anybody know how can I do that?

Mathia
 
Physics news on Phys.org
baby steps...baby steps...


I don't know matlab, but I would suggest to first focus on getting the eval call to work, in the first place...then, you can worry about the loop, etc.

So, just try eval by itself until it is working...does it need a comma between the two arguments? I know you mean to concatenate, but it still may need to be separated by a comma in the list and EVAL will glue them togehter...that what EVAL does, I think.

Also, I read that EVAL takes any valid MATLAB statement...is what you provide to EVAL a valid statement? It is not really much of a command or assignment...will it work? maybe you have to assigne it to something and it will still return the value...

...play around, don't be shy...you are not going to break anything.
 
I tested eval. It works correctly, but i have that error wen I use exist eval...!
 
You may be overseeing the context within which the result is being used. 'exist' expects a string, not a command output, which is what eval returns.

You may need something like "strcat" instead...this is purely a string concatenation function...this may be all you need, not really eval.
 

Similar threads

Replies
5
Views
2K
Replies
4
Views
1K
Replies
9
Views
3K
Replies
5
Views
2K
Replies
1
Views
4K
Replies
4
Views
3K
Replies
4
Views
2K
Replies
2
Views
2K
Back
Top