For loop to extract every 3rd column out of matrix and assign as variable name

조회 수: 4 (최근 30일)
I have a matrix that is 6001 x 72. I want to iterate through the matrix to extract every 3rd column, from 1:72, and assign it to a variable name, such as X1, X2,...,X24. How can I do this?
I have tried a for loop, but I keep getting error messages. I am a beginner in Matlab.
Thanks!
  댓글 수: 2
Stephen23
Stephen23 2019년 6월 25일
편집: Stephen23 2019년 6월 25일
"...assign it to a variable name, such as X1, X2,...,X24. How can I do this?"
Do NOT do this.
Accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read these to know why:
You should use indexing. Inexing is neat, easy to debug, and very efficient.
Anna M
Anna M 2019년 7월 2일
Thank you! I will definitely look into that.

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

채택된 답변

James Tursa
James Tursa 2019년 6월 24일
Do not do this! This will only lead to headaches downstream in your code for processing these variables (you will need to use more eval( ) statements etc) and will be a nightmare to debug. There are much better alternatives. E.g.,
  댓글 수: 2
infinity
infinity 2019년 6월 25일
Hello, Thank @James Tursa for mentioning this issuse of eval function.
I recommend @Anna M to refer these solutions.
Anna M
Anna M 2019년 7월 2일
Thank y'all for the help. It is appreciated

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

추가 답변 (1개)

infinity
infinity 2019년 6월 24일
Hello,
Here is an example that you can refer
for i = 1:24
v = genvarname(['X' num2str(i)]);
eval([v '= A(:,3*i);']);
end
where A is your matrix.

카테고리

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