smyslov
smyslov

Reputation: 1275

Varying sized rows in matrix - matlab

Consider I have a vector a of size 5x1 and I pad zeros at the beginning of this vector. The number of zeros are generated using the randn function. Due to the randn, the vector is padded by a random number of zeros in a for loop. I would like to store these varying size vectors in a single matrix and I am unable to figure a way how to do this (other than fixing the size of the matrix before hand. Here is a MWE for the same:

a = rand(5,1)
for ii = 1 : 6
delay = round(abs(randn(1,1)));
shifted_a = [zeros(delay,1);a];
temp_mat(:,ii) = shifted_a    
end

In the second iteration, matlab will definitely throw an error due to the assignment mismatch at temp_mat(:,ii) = shifted_a. Is there a way I can have all these vectors in a matrix without having to fix the size of the matrix in advance.

Upvotes: 2

Views: 195

Answers (2)

Nemesis
Nemesis

Reputation: 2334

To complete the question based on @kkuillas answer:

You can find out the maximum length of the columns by

max_len = max(cell2mat(cellfun(@(x)size(x,1),temp_mat,'UniformOutput',false)));

and then create your final matrix

fin_mat = zeros(max_len,size(temp_mat,2));

for i = 1:length(temp_mat)
    fin_mat(1:size(temp_mat{i},1),i) = temp_mat{i};
end

(maybe the for-loop can be replaced...).

Upvotes: 1

kkuilla
kkuilla

Reputation: 2256

Use a cell array instead.

a = rand(5,1);
for ii = 1 : 6
   delay = round(abs(randn(1,1)));
   shifted_a = [zeros(delay,1);a];
   temp_mat{ii} = shifted_a;  % // Use a cell array instead
end

And if you want to join them, you can use vertcat to make one long vector.

B=vertcat(temp_mat{:});

Upvotes: 2

Related Questions