How to input an array into a matrix through looping?
显示 更早的评论
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
回答(2 个)
>> x = [2 4 6 8 10 12 14 16 18 20];
>> A = repmat(x(:),1,1000);
>> x = 2:2:20;
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 个评论
jefkei92
2015-5-24
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!