Defining a non-predetermined number of variables inside a loop
이전 댓글 표시
Hi,
I have the following code for loading all the files from a given folder:
function out = prepfold
in = input('what is the folder name? ');
d = dir(in);
cd(in)
dindex = find(~[d.isdir]);
for j = 1:min(1,length(dindex))
fname = d(dindex(j)).name;
load(fname)
%make new variable named Sj, as in S1, S2, S3, S4, S5... and analyze them
end
How do I perform the commented line? I am only reading .txt files with numerical data, so I get only double type variables. Since I don't know the number of files before hand, I cannot preallocate. I don't want to prepare a single file padded with zeros, and I am not very good with cells, arrays or the likes, so help to prepare single variables would be greatly appreciated. Cheers.
채택된 답변
추가 답변 (2개)
Image Analyst
2013년 8월 27일
Use S(j) or S{j} instead of S1, S2, S3, etc. Use S(j) if you're setting it to a single number. Use S{j} if you're setting it to a string, a structure, an array, etc. See the FAQ on cells for an explanation of cells.
Doesn't j just go up to min(1,length(dindex))? So why can't you preallocate S?
maxJ = min(1,length(dindex));
S = zeros(1, maxJ); % or
S = cell(1, maxJ);
What do you mean when you say "I don't want to prepare a single file padded with zeros" - why would you be preparing a file??? I don't even see an fopen() or fprintf() in there. What file are you talking about? Some kind of output file? Or just a temporary scratch file that you think you need for some reason?
Why are you doing
in = input('what is the folder name? ');
??? Why not use uigetdir()? It's easier for your user to pick one than to have to type one in and possibly not know the name or misspell it.
It's better to load a mat file into a structure than to just call it.
storedStructure = load(fname);
myVariable = storedStructure.myVariable; % or whatever.
lastFolderUsed = storedStructure.lastFolderUsed; % or whatever.
Your function never declared "out" so it will throw an exception. Put this as the first line inside the function
out = [];
Then go ahead and define it however you want to.
Tom
2013년 8월 27일
0 개 추천
댓글 수: 1
Walter Roberson
2013년 8월 27일
for K = 1 : length(d)
fn = ['data_from_file' str2num(K)];
mydata.(fn) = load(d.name);
end
No cell, no eval.
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!