MATLAB Answers

Anna M

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

Asked by Anna M
on 24 Jun 2019
Latest activity Commented on by Anna M
on 2 Jul 2019
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.


"...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.
Thank you! I will definitely look into that.

Sign in to comment.

2 Answers

Answer by James Tursa
on 24 Jun 2019
 Accepted Answer

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.,


Hello, Thank @James Tursa for mentioning this issuse of eval function.
I recommend @Anna M to refer these solutions.
Thank y'all for the help. It is appreciated

Sign in to comment.

Answer by infinity
on 24 Jun 2019

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

  1 Comment

Sign in to comment.