filling array with different vectors

3 views (last 30 days)
Rick
Rick on 15 Sep 2016
Commented: José-Luis on 15 Sep 2016
Hey all,
i have a problem with filling an array with data. i have 6 vectors that i want to get into 1 array. they arent the same size, so i created an array with zeroes with the size of the largest vector. the code is:
X = zeros(maxsize,6)
for i = 1:length(X5)
X(i,1) = X5(i)
end
for i = 1:length(X10)
X(i,2) = X10(i)
end
for 1 = 1:length(X15)
X(i,3) = X15(i)
end
....
The code creates 1 array filled with all the data and some zeroes, which is what i want. The problem is that this is a lot of code for something this simple. I have to create 3 arrays this way.. My question: is there a way to do this more efficient? I'm not that experienced with matlab, so maybe i missed a really easy solution..
Thanks in advance!

Accepted Answer

José-Luis
José-Luis on 15 Sep 2016
Edited: José-Luis on 15 Sep 2016
x1 = rand(1,5);
x2 = rand(1,7);
x3 = rand(1,10);
result = [{x1};{x2};{x3}];
maxsize = max(cellfun(@(x) numel(x),result));
result = cell2mat(cellfun(@(x) {[x,zeros(1,maxsize-numel(x))]},result));
Also, please learn to use cell arrays instead of using variables like x1,x2,...,xn. It will save you very many headaches in the future.
  2 Comments
Rick
Rick on 15 Sep 2016
Thanks! Like i said, im not that experienced yet. Didnt even think of cell arrays. I'll look into that for sure.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!