How to input an array into a matrix through looping?
27 views (last 30 days)
Show older comments
I am trying to take an looped array of 10 integers, such as x= [ 2 4 .... 20] below (generated from a loop - so each will be different), rotate it (if needed), and then populate a 10:1000 matrix, keeping each 10 integers looped array output. In other words, no just repeating the output 1000x. I have been experimenting to no avail with the code below. It seems to produce the matrix correctly, but I have yet to be able to populate it with the array of 10, 1000 times across.:
clear all clc
R = 10 %number of rows
C = 1000 %number of columns
A = zeros(R,C)
x = [2 4 6 8 10 12 14 16 18 20];
z = rot90(x)
for i = 1:R
for j = 1:C
A(i,j)= z
end
end
0 Comments
Answers (2)
Stephen23
on 22 May 2015
Edited: Stephen23
on 22 May 2015
Although the original question shows one vector being repeated, based on your comments to my first answer and the edited question you are actually trying to allocate different vectors with each iteration. The two things you need to do are:
- preallocate the output array before the loop
- use indexing to allocate the values in the loop
Note that the complete vector (its orientation does not matter) can be allocated using colon notation, like this:
A = zeros(10,1000);
for k = 1:1000;
vector = ... calculations here!
A(:,k) = vector;
end
2 Comments
Stephen23
on 25 May 2015
Edited: Stephen23
on 25 May 2015
You could move the max and tabulate outside of the loop, if you want them to be performed on the entire matrix. Currently the code does not make much sense, as the scalar r is going to be them same value on every iteration, and calling tabular on a scalar is anyway pointless.
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!