Storing vectors from a for loop, into a 2d matrix.
4 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!