Rmeow
Rmeow

Reputation: 113

From a for loop, how do I store different length vectors into a single matrix

I'm new to Matlab and programming in general. I'm trying to write a for loop where I'm able to keep the generated uneven length vectors into a matrix.

Here is my basic for loop:

G1 = [1 2 3 4];
for G1 = G1(1:end)
y = randn(1,G1)
end

I like to keep all values of y in the successive rows of a matrix like this:

enter image description here

I tried initializing y to a zero matrix first and running the for loop:

G1 = [1 2 3 4];
for G1 = G1(1:end)
y = zeros(4,4)
y(G1,:) = randn(1,G1)
end

The error is "Subscripted assignment dimension mismatch." I have also tried other variations of the for loop, all with initializing the zero matrix first but I received the same error message. How can I go about doing this? Thanks!

Upvotes: 0

Views: 312

Answers (1)

brodoll
brodoll

Reputation: 1881

A short answer to your problem is:

y = tril(randn(4));

This will return the lower triangular part of a square matrix of size 4 of normally distributed random numbers.

Note I hard coded the 4, but you could easily replace it with max(G1) or length(G1).

As for your first code block, you should notice:

  1. You are overwriting the variable G1 when you define your for loop as such. Use another variable as the counter, such as counter for instance;
  2. The variable y is overwritten each loop. You seem to have noticed it when you tried to fix in your second attempt. But you haven't taken into account that randn(1,G1) will give you different length vecors each iteration, which will cause dimension mismatch errors if you do not pay attention.

For your second code snippet:

  1. y = zeros(4,4) is initialized inside the loop. It means any data you assign to it afterwards is wiped out each loop. You need to initilize your vector before the for loop;
  2. Same observations for the first snippet also apply.

Finally, you should have a complete code as the following after the corrections:

G1=1:4;
y=zeros(4);
for counter=1:4
y(counter,1:counter)=randn(1,counter);
end
>> y
y =

  -0.43911   0.00000   0.00000   0.00000
   0.09520  -0.21825   0.00000   0.00000
   0.32569   1.04944  -1.19666   0.00000
   0.25531   0.68336  -1.02413   0.72696

Notice the indexing in y(counter,1:counter)=randn(1,counter); to avoid the mismatch errors.

Upvotes: 2

Related Questions