how to code variable to code

like in box name have s1 s2 s3 s4 s5 s6 .. sn
s1 = 1
s2 = 2
s3 = 3
sn = n
**************************
for i=1:n
s<i> do something
end
************
behind s<> how to code variable to code

Answers (1)

madhan ravi
madhan ravi on 3 Jul 2019

8 Comments

sry i can't find my answer T^T
The answer is "Don't DO That!"
There are ways to do it, but there are very very few good reasons to do it considering the alternatives.
pls. can u teach me? cos my algorithm need to use this function
Explain what you want to do. Then we can help you solve your actual problem.
i want to know how to use for loop for varible
example >> i create
-------------------------------------
for i=1:1000
eval(sprintf('s%d = i+1', i));
end
------------------------------------------
i will got s1 ,s2 ,s3 , ...sn on work space.
but it too many n i can't typing. i want to use for loop to help but i dont know about code.
-----------------------------------------------------------------------
for i=1:n
s( in this blacket how to tell matlab when i use for loop )
i know i can typing
s1 = do something
s2 = do something
s3 = do something
but i have a lot of n. i want for loop to do this for me.
like
s(i) = do something <<< for easy than typing
end
-----------------------------------------------------------------------
thank you.
I think you already identified the problem, do not create variables s1,s2,s3 i n the first place.
s=ones(1000,1);
for i=1:1000
s(i)=i+1;
end
@Anantachai Chotkamsri: what is stopping you from just using indexing?
Indexing is simple, neat, and very effiicient (unlike what you are trying to do).
Indexing is also explained in the introductory tutorials:
and also explained in the link that madhan ravi gave you.
thank you so much for help everyone. <3

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!