filling array with different vectors
3 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
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.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!