Defining a non-predetermined number of variables inside a loop
5 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
採用された回答
その他の回答 (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.
0 件のコメント
Tom
2013 年 8 月 27 日
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.
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!