Writing results of a loop to a vector

I'm trying to create a loop that writes filenames, and it works but overwrites the variable. How do I get it to save the results to an entry in a vector?
%% Problem 4
myfile=zeros(1000,1);
for q=1:1000
if q<=9
myfile=sprintf('data_00000%d.dat',q);
elseif(q>9 && q<=99)
myfile=sprintf('data_0000%d.dat',q);
elseif(q<=999 && q>99)
myfile=sprintf('data_000%d.dat',q);
else
myfile=sprintf('data_00%d.dat',q);
end
end
I know im supposed to add (q) as a function of a variable but I don't know where. If I add it after "myfile" I get the error: "In an assignment A(I) = B, the number of elements in B and I must be the same.

 Accepted Answer

You need to assign them to an array:
for q=1:1000
if q<=9
myfile(q,:)=sprintf('data_00000%d.dat',q);
elseif(q>9 && q<=99)
myfile(q,:)=sprintf('data_0000%d.dat',q);
elseif(q<=999 && q>99)
myfile(q,:)=sprintf('data_000%d.dat',q);
else
myfile(q,:)=sprintf('data_00%d.dat',q);
end
end
myfile(1,:)
myfile(10,:)
myfile(100,:)
myfile(1000,:)
This works because they’re all the same length. (If you encounter a situation where they aren’t, use a cell.)

2 Comments

OH! Thank you! I didn't know how to format the part you put in. However im still getting a dimension mismatch. Currently looking for a solution.
My pleasure!
I believe I know where your dimension mismatch originates. I forgot to specifically mention that I eliminated your preallocation statement:
myfile=zeros(1000,1);
because it defines myfile as a 1000 row by 1 column double array. Your myfile array ends up as a (1000x15) character array.
If you want to preallocate myfile, I suggest instead using this statement:
myfile = repmat(blanks(15),1000,1);
When I timed it just now, without the preallocation, the loop alone requires:
Elapsed time is 0.021684 seconds.
with the preallocation,
Elapsed time is 0.018693 seconds.
and including the preallocation in the timing,
Elapsed time is 0.024179 seconds.
So it’s up to you if you want to preallocate. I have no strong feelings on the subject in your application.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 29 Apr 2014

Edited:

on 29 Apr 2014

Community Treasure Hunt

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

Start Hunting!