Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Select variable automatically in matlab

  1. May 20, 2012 #1
    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)]));
    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?
    Best regards,
  2. jcsd
  3. May 21, 2012 #2
    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 statment? 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.
  4. May 21, 2012 #3
    I tested eval. It works correctly, but i have that error wen I use exist eval...!
  5. May 21, 2012 #4
    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook