2

I am trying to concatenate a variable with a string. For example I want to get d1, d2 and d3.

I know that to concatenate 'd' with 1 , 'd' with 2 and 'd' with 3 , it is necessary to convert 1, 2 and 3 to string. The code below work very well :

['d' num2str(1)] = 4;
['d' num2str(2)] = 5;
['d' num2str(3)] = 6; 

But when I tried the code below:

for i=1:3
['d' num2str(i)] = i+3;
end

Unfortunately I always get the error : An array for multiple LHS assignment cannot contain LEX_TS_STRING

Any help will be very appreciated.

1
  • This is very strongly discouraged by everyone, including Mathworks. It's much better to use d(1), d(2) etc. Of course, if you're writing this to a file and have to have it on this format, I guess you can't avoid it. However, I would still recommend keeping it on the format d(ii) in MATLAB, and use evalc() when you're writing it to the file. Commented Mar 8, 2014 at 11:48

1 Answer 1

3

Use EVALC -

for i=1:3
    evalc(['d' num2str(i) '=' num2str(i+3)]);
end

EDIT 1: If d1=3; and you need to get d2 = d1+4 and d3 = d2+4;, use this -

d1 = 3;
for i=2:3
    evalc(['d' num2str(i) '=d' num2str(i-1) '+4']);
end
Sign up to request clarification or add additional context in comments.

2 Comments

And if I have for example d1=3; and I want to get d2 = d1+4 and d3 = d2+4; how to edit your code. Please can you add this to your code above ? thanks in advance
I get Undefined function or variable 'd2' and 'd3' :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.