How can i creat varibales, varible1, viable2, into loop

1 view (last 30 days)
Hello,
I am a beginer of Matlab. I have a problem about creating the loop. I upload the raw data as column vectors from excel. then I get the Varibles as StorageModulus1, StorageModulus2,StorageModulus3,StorageModulus4 until StorageModulus15.
I would like to creat a Matrix. Here is my code:
for
A=0:2:15;
B=1:2:15;
C=1:length(A);
eval(sprintf('StorageModulus%A = A',A))
eval(sprintf('StorageModulus%B = B',B))
SMM(C)= [StorageModulus(A),StorageModulus(B)]
end
but this code doesnot work and it always shows that StorageModulus is undefined varibales.
Can someone help me to slove this problem?
  1 Comment
Stephen23
Stephen23 on 24 Oct 2019
Edited: Stephen23 on 24 Oct 2019
"I have a problem about creating the loop"
Actually your problem is the idea that you should dynamically name variables:
"I am a beginer of Matlab."
Then today is the best day to start to learn how to use MATLAB properly.
Numbering variables is a sign that you are doing something wrong with your code. Accessing numbered variables is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug.
You should use indexing. Indexing is simple, easy to debug, and very efficient (unlike what you are trying to do).

Sign in to comment.

Answers (1)

John D'Errico
John D'Errico on 24 Oct 2019
Simple answer, don't do it. You even state that you are a beginner. So instead, learn to use MATLAB properly. Use vectors, use arrays. Use the tools of MATLAB as they are designed to be used.
Or, you can continue down the path of creating variable names with numbers like that, creating buggy code that will be incredibly slow. It will be hell to maintain. Feel free to go down that path. But then don't come crying asking how to speed up your code, or asking how to fix the bugs in your code.
The cjhoice would be yours. I'd suggest learning to use MATLAB instead.
  2 Comments
feihong xu
feihong xu on 24 Oct 2019
But coud you please offer me a solution to this problem? Then I know which code I should use for next time?
Stephen23
Stephen23 on 24 Oct 2019
Edited: Stephen23 on 24 Oct 2019
"Then I know which code I should use for next time?"
Next time (and this time) do NOT name variables, use simple and efficient indexing instead.
Given that A is a vector, what do you expect
eval(sprintf('StorageModulus%A = A',A))
to do? Rather than incorrectly guessing basic MATLAB usage, your time would be much better spent doing the introductory tutorials:

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!