Filter löschen
Filter löschen

Convert string to variable

6 Ansichten (letzte 30 Tage)
Maine MacConville
Maine MacConville am 5 Mär. 2016
Beantwortet: Rushil Shah am 4 Jun. 2020
Just to be clear: this isn't to generate a string name (unless this would solve my problem).
I've a script that reads some images into the workspace - for simplicity let's say there are 3 and they're called pic1, pic2, and pic3. Later I have a loop function that should do some work on each of the pictures. So for a "for" loop from 1 to N, I'd want picN = pic1 when N = 1, picN = pic2 when N = 2 etc. I've tried typing picN = sprintf('pic_%d', N) but this is giving me a string output, when what I want to do is to say that a newly defined variable is equal to an already-known variable.
Any help would be appreciated.
  3 Kommentare
rajasweta datta
rajasweta datta am 30 Mai 2017
Hii I guess you have probably figured it out but here it goes.. you can save the variable name as string in a array string={'pic1','pic2','pic3'}; for i=1:3 pictoprocess=eval(string{i}); %do all your processing on pictoprocess end
Jan
Jan am 30 Mai 2017
Bearbeitet: Jan am 30 Mai 2017
@rajasweta datta: Do not do this. See https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval and hundrets of corresponding thread. eval is a shot in your knee. eval is not a solution, but it supports the very bad idea to hide indices in the names of the variables.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Star Strider
Star Strider am 5 Mär. 2016
If I understand your Question correctly, you are about to invoke the wrath of those here who are absolutely opposed to dynamic variables (although this would be appropriate if frequently overstated).
With respect to the names, you could use the strcmp function. I cannot understand what else you want to do sufficiently to provide precise Answers.

Walter Roberson
Walter Roberson am 5 Mär. 2016
pics = {pic1, pic2, pic3};
for i = 1 : 3
picN = pics{i};
...
end

Rushil Shah
Rushil Shah am 4 Jun. 2020
You can change the code shown in the above link.
Give values in your case picture path and assign it as the variable name.
Although it'll be in char data type.
I hope this helps you to solve your problem.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by