filling array with different vectors

3 次查看(过去 30 天)
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!

采纳的回答

José-Luis
José-Luis 2016-9-15
编辑:José-Luis 2016-9-15
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 个评论
Rick
Rick 2016-9-15
Thanks! Like i said, im not that experienced yet. Didnt even think of cell arrays. I'll look into that for sure.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by