Storing vectors from a for loop, into a 2d matrix.

6 views (last 30 days)
Greetings all,
Hopefully this is a relatively trivial issue, i have observed this short for loop:
>> for r = 1 : 10 vec = [10:20]+r mat(r,1) = vec end
which creates 10 vectors, e.g:
11 12 13 14 15 16 17 18 19 20 21
and stores them in a matrix like this:
11 12 13 14 15 16 17 18 19 20 21
12 13 14 15 16 17 18 19 20 21 22
13 14 15 16 17 18 19 20 21 22 23 ....etc
When i am trying to utilise this for my own project, i need it to be of the form:
for r = 1 : 5 : 16 vec = [10:20]+r mat(r,:) = vec end
which i thought would give:
11 12 13 14 15 16 17 18 19 20 21
16 17 18 19 20 21 22 23 24 25 26 etc.
But i am getting:
11 12 13 14 15 16 17 18 19 20 21
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
16 17 18 19 20 21 22 23 24 25 26
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
Where do all these 0's erupt from? i must plot the array without the zero's because my actual data is much larger (approx for k = 1: 500: 1000000) and exponential number of 0's just exceeds matlab capabilities.
anyone know a better way of storing these results in a 2d array? thank you, much obliged.
David

Accepted Answer

Sean de Wolski
Sean de Wolski on 6 Feb 2013
Well when r = 1: you index into
mat(r<:)
But then the next iteration r = 6 and you have:
mat(r,:)
So you need to keep a counter:
cnt = 0;
for r = 1:5:16
cnt = cnt+1;
mat(cnt,:) = whatever
end
  1 Comment
David Mehr
David Mehr on 6 Feb 2013
/this is just what i needed, a simple and practical solution. Very grateful for this. I'm very new to MATLAB (and programming in general) but this really helps me get on with my studies. Thank you! :D

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!