How to use variable names/strings in a For cycle

조회 수: 6 (최근 30일)
Hugo
Hugo 2022년 1월 25일
답변: Image Analyst 2022년 1월 26일
Hi,
I have the following code:
B1=matrix(:,1)
B2=matrix(:,2)
B3=matrix(:,3)
B4=matrix(:,4)
B5=matrix(:,5)
I would like to replace the 5 lines of code above by a "For" cycle.
However, I get an error when I try to compile the following code:
For i=1:5
"B"+i=i
end
The error is:
Incorrect use of '=' operator. Assign a value to a variable using '=' and compare values for equality using '=='.
How can I define variable names/strings correctly?
I thank you in advance,
Best regards,
  댓글 수: 1
Stephen23
Stephen23 2022년 1월 25일
편집: Stephen23 2022년 1월 25일
"How can I define variable names/strings correctly?"
Dynamically naming variables is one way that beginners force themselves into writing slow, complex, inefficient, obfuscated code that is buggy and difficult to debug. Here are some reasons why:
The simple and efficient MATLAB approach is to use indexing. Is there a particular reason why you cannot use indexing?
Here is simpler, much more efficient code that actually works (unlike your code):
for k = 1:5
vec = matrix(:,k);
end

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

채택된 답변

KSSV
KSSV 2022년 1월 25일
You need not to do that.....it is sheer waste of time and not a good coding practise. You can save the data into a 3D matrix. This is preferred.
B = zeros(2,2,5) ;
B(:,:,1) = rand(2) ;
B(:,:,2) = rand(2) ;
B(:,:,3) = rand(2) ;
B(:,:,4) = rand(2) ;
B(:,:,5) = rand(2) ;
You can access them by using B(:,:,1),..B(:,:,5)

추가 답변 (2개)

Voss
Voss 2022년 1월 25일
Here is how you can do it:
matrix = magic(5);
for i = 1:5
eval(['B' num2str(i) '=matrix(:,' num2str(i) ');']);
end
whos()
Name Size Bytes Class Attributes B1 5x1 40 double B2 5x1 40 double B3 5x1 40 double B4 5x1 40 double B5 5x1 40 double i 1x1 8 double matrix 5x5 200 double
Here is what you should do instead:
clear variables
matrix = magic(5);
B = cell(1,size(matrix,2));
for i = 1:5
B{i} = matrix(:,i);
end
whos()
Name Size Bytes Class Attributes B 1x5 720 cell i 1x1 8 double matrix 5x5 200 double
celldisp(B)
B{1} = 17 23 4 10 11 B{2} = 24 5 6 12 18 B{3} = 1 7 13 19 25 B{4} = 8 14 20 21 2 B{5} = 15 16 22 3 9
Or:
clear variables
matrix = magic(5);
B = num2cell(matrix,1);
whos()
Name Size Bytes Class Attributes B 1x5 720 cell matrix 5x5 200 double
celldisp(B)
B{1} = 17 23 4 10 11 B{2} = 24 5 6 12 18 B{3} = 1 7 13 19 25 B{4} = 8 14 20 21 2 B{5} = 15 16 22 3 9

Image Analyst
Image Analyst 2022년 1월 26일

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by