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
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
Tom 2013년 8월 27일

0 개 추천

Thank you both for the replies. Apparently it's impossible to avoid using a cell, unless I am willing to use eval. Image Analyst, thank you for the other helpful comments as well (I meant a zero-padded (or NaN-padded) variable, not file, which would be the result if I tried to prepare a matrix from vectors of variable length. Again, I hate cells, as I can't work with them intuitively like with matrices).

댓글 수: 1

for K = 1 : length(d)
fn = ['data_from_file' str2num(K)];
mydata.(fn) = load(d.name);
end
No cell, no eval.

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

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

질문:

Tom
2013년 8월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by