filling array with different vectors

3 visualizaciones (últimos 30 días)
Rick
Rick el 15 de Sept. de 2016
Comentada: José-Luis el 15 de Sept. de 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!

Respuesta aceptada

José-Luis
José-Luis el 15 de Sept. de 2016
Editada: José-Luis el 15 de Sept. de 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 comentarios
Rick
Rick el 15 de Sept. de 2016
Thanks! Like i said, im not that experienced yet. Didnt even think of cell arrays. I'll look into that for sure.
José-Luis
José-Luis el 15 de Sept. de 2016
My pleasure.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by