필터 지우기
필터 지우기

Storing a vector in a loop each time with a different name

조회 수: 2 (최근 30일)
Siddhant Chandra
Siddhant Chandra 2018년 8월 10일
댓글: Siddhant Chandra 2018년 8월 10일
for k = 1:10
FileName1 = ['EqvStr_',num2str(k),'.csv'];
filename1 =fullfile('E:\ANSYS_FILES\BigKB', FileName1);
A = xlsread(filename1,'A2:E1000');
vectorname = ['a',num2str(k)];
vectorname = A(:,1);
end
disp(a1)
disp(a2)
disp(a3)
disp(a4)
disp(a5)
disp(a6)
disp(a7)
disp(a8)
disp(a9)
disp(a10)
So I am running the above code and MATLAB gives me an error message saying "Undefined function or variable 'a8'". It is weird because it IS showing me the results if I comment out the a8, a9, and a10 lines from the code but gives me the error message if not. There are a 1090 files in the folder in that name format and I am just testing the code with the first 10 but it is showing me this error. Can anyone please help me understand what the problem here is?
  댓글 수: 2
Stephen23
Stephen23 2018년 8월 10일
"Can anyone please help me understand what the problem here is?"
Bad code design. Much better code design would simply use simpler, more efficient indexing with a cell array, exactly as the MATLAB documentation shows:
What you are doing will force you into writing slow, buggy, complex code which is harder to debug:
Siddhant Chandra
Siddhant Chandra 2018년 8월 10일
Thanks Stephen! I will improve it.

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

채택된 답변

James Tursa
James Tursa 2018년 8월 10일
편집: James Tursa 2018년 8월 10일
This is not the best way to do this in MATLAB. There are many, many posts on this site explaining why. Instead, you should use cell arrays. E.g.,
A{k} = xlsread(filename1,'A2:E1000');
Then downstream in your code simply use A{k} instead of the a1, a2, etc that you are currently using. See this link:
  댓글 수: 6
Stephen23
Stephen23 2018년 8월 10일
편집: Stephen23 2018년 8월 10일
@Siddhant Chandra: try it and find out: assuming that C does not exist, try this:
C{4} = 1
What does it create?
But your question is actually a good one, because to make the code clear, efficient, and to prevent interference from existing variables you should preallocate the cell array before the loop, like this:
N = 10;
C = cell(1,N); % preallocate!
for k = 1:N
...
C{k} = xlsread(...);
end
Then it is unambiguous what size C has, and what the indexing refers to. Note that the MATLAB documentation clearly shows the cell array being preallocated before the loop:
You can read about array preallocation here:
Using clear is not recommended for this, it is better to preallocate.
Siddhant Chandra
Siddhant Chandra 2018년 8월 10일
Got it! Thank you so much for your help Stephen! Thank you for the knowledge

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by