How to add iteration in a string (make multiple strings using iterations without indexing) ?

52 次查看(过去 30 天)
I have been wondering for a loooong time how to acheive this. (I am a beginner by the way so please bear with me)
The problem is shown in the sample code below. I want the numerical "i" to be used in the string to output: "png1", "png2", and so forth.
Of course the code doesn't work.
I know of a way; to make a matrix in advance with string then access the matrix but this won't work with a while loop.
I thank you so much in advance.
for i = 1:4
matlab = "png(i)"
end

采纳的回答

the cyclist
the cyclist 2021-10-25
编辑:the cyclist 2021-10-25
Here is one way:
for i = 1:4
matlab = sprintf("png%d",i)
end
matlab = "png1"
matlab = "png2"
matlab = "png3"
matlab = "png4"
Here is another, but wanted to show the first way, which can be more versatile for other ways to build strings and/or character arrays.
for i = 1:4
matlab = "png"+i
end
matlab = "png1"
matlab = "png2"
matlab = "png3"
matlab = "png4"
  5 个评论
Image Analyst
Image Analyst 2021-10-25
@Steven Lord, neat trick. Good to know. Thanks for sharing.
matlab is a reserved variable name so he should use a different variable name. Just type matlab on the command line then dot and and the tab key to see all the methods and properties of the matlab object/class. Another neat trick.
Haisam Khaled
Haisam Khaled 2021-10-26
@Image Analyst DUUUDE this was the one that started it all, I saw it once somewhere, but somehow forgot it and no matter what I tried, I never thought of this one. THANK YOU AGAIN, now I have immense knowledge <3

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2021-10-25
If I understand you correctly you want to dynamically/programmatically create named variables and then access them later by that created name. The reasons against this are discussed in the FAQ:
  1 个评论
Haisam Khaled
Haisam Khaled 2021-10-25
Hey man, first of all, I am a big fan of you, you answered many questions of other people that I benefitted a lot from.
Second, I know my mind is that of a beginner and yours is so advanced and much smarter than me. I didn't explain the problem well, regaardless someone understood my stupid explanation and provided a solution, I thank you soooo much for your effort.
P.S. this article was helpful <3

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by