Why looping just save the last value, not every loop ?

Dear all, I have .TXT data with name ZA000060.TXT, ZA000120.TXT, ZA000180.TXT, ZA000240.TXT, ZA000300.TXT. I load those data with these syntax
for k=60:60:300
aa = sprintf('%03d',k);
filename = sprintf('ZA000%03d.TXT', k);
ZA{k}=load(filename);
end
for k = 1:length(ZA)
x(:) = ZA{k};
% do stuff with x
end
but why the result just store the last data on ZA{k} ? not every data store after looping. how to fix this ?? any help would be great. Best regard,

 Accepted Answer

Try using a separate vector to store the values:
V = 60:60:300;
C = cell(size(V));
for k = 1:numel(V)
filename = sprintf('ZA000%03d.TXT', V(k));
C{k} = load(filename);
end
The original answer used the values of V directly as indices into the cell array, which produced lots of empty cells because only every sixtieth cell had something in it. This is not a good way to code, and it is not a very robust solution to use data values as indices.

5 Comments

ok, you give me this code before
V = 60:60:300;
S = struct('AAA',{});
for k = 1:numel(V)
S(k) = load(...,'AAA');
end
but there is error shows up
end
|
Error: Expression or statement is incorrect--possibly unbalanced (, {,
or [.
also for this part
S(k) = load(...,'AAA');
what exactly that I have to write ?? Thanks
I put the ellipses (those three dots):
S(k) = load(...,'AAA');
to indicate that you have to put the filename there, like this:
S(k) = load(filename,'AAA');
I wanted to show the important parts of this code, and not focus on things like the filename. If you put the filename there then it will work.
I wrote again like this
V = 60:60:300;
S = struct('AAA',{});
for k = 1:numel(V)
S(k) = load(['ZA000060.TXT'],'AAA');
end
the error is Assignment between unlike types is not allowed. The name of my data is ZA000060.TXT, ZA000120.TXT, .... ZA000300.TXT
Thanks a lot
That was my mistake: I did not notice that you are trying to load text file, not a mat file. You should load the data into a cell array, exactly like the original answer:
C = cell(size(V));
for k = 1:numel(V)
filename = sprintf('ZA000%03d.TXT', V(k));
C{k} = load(filename);
end
For ascii data load does not return a structure, just a numeric matrix. This can be stored in the cell array.
oke stephen thanks a lot

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!