Matlab problem merging arrays in for loop

from a simple code in Matlab, using a for loop (for i=1:10), I get the following 2x1 arrays:

tables from for loop

I'd like to put them all together into a 20x1 array, but I get this:

final table

As I mentioned, I'd like my final array to have the dimensions 20x1.

The code is:

clc
clear all
t = 1:10;
u_x = 10;
u_y = 20;
u = [u_x; u_y];

W = [];
for i=1:1:10
    w = u.*i + rand(2,1)
    W(i,:) = w;
end
W

Upvotes: 0

Views: 129

Answers (1)

AboAmmar
AboAmmar

Reputation: 5559

Initialize W as you want, W = zeros(20,1), and populate inside the loop as W(2*i-1:2*i) = w since the size of w is known to be 2x1.

clc
clear
t = 10;
u_x = 10;
u_y = 20;
u = [u_x; u_y];
U = repmat(u, [1,t]);

W = zeros(20,1);
for i = 1:10
    w = u.*i + rand(2,1);
    W(2*i-1:2*i) = w;
end
W

You actually don't have to use loops, this one-liner will do the same:

W = reshape(repmat(1:t,2,1) .* U + rand(2,10), [20 1])

Edit: The above loop can be modified to work for any range and any step.

range = 1:0.5:10;
W = zeros(2*length(range),1);
for i = 1:length(range)
    w = u.*range(i) + rand(2,1);
    W(2*i-1:2*i) = w;
end
W

Similarly, for the vectorized solution:

L = length(range);
U = repmat(u, [1,L]);
W = reshape(repmat(range,2,1) .* U + rand(2,L), [], 1])

Upvotes: 1

Related Questions