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

조회 수: 1 (최근 30일)
feihong xu
feihong xu 2019년 10월 24일
편집: Stephen23 2019년 10월 24일
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
Stephen23
Stephen23 2019년 10월 24일
편집: Stephen23 2019년 10월 24일
"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).

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2019년 10월 24일
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
feihong xu
feihong xu 2019년 10월 24일
But coud you please offer me a solution to this problem? Then I know which code I should use for next time?
Stephen23
Stephen23 2019년 10월 24일
편집: Stephen23 2019년 10월 24일
"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:

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by