Creating a Matrix with for loop
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Philipp
el 30 de Abr. de 2020
Hi together,
I have a question about creating a matrix. For me, at the moment, it is impossible to solve, I just don't get it.
I've got a matrix X
2x9 double
X = [2 1 2 10 3 0 0 0 0,
2 2 3 20 5 0 0 0 0]
and I have a vector z=[2 3];
Now I would like to create a matrix T , which looks like this
5x9 double
T= [2 1 2 10 3 0 0 0 0,
2 2 3 10 3 0 0 0 0,
2 3 4 20 5 0 0 0 0,
2 4 5 20 5 0 0 0 0,
2 5 6 20 5 0 0 0 0];
So this means 2x (z(1)) the first row of X and 3x (z(2)) the 2nd row of X.
In the end, I don't know the final size of X and z and don't know the content, but this is just a small example.
Hope anybody can help. Thank you.
Cheers,
Philipp
2 comentarios
Respuesta aceptada
Rik
el 30 de Abr. de 2020
This code should get you close to what you need. Adapt as needed.
X =[2 1 2 10 3 0 0 0 0;
2 2 3 20 5 0 0 0 0];
z=[2 3];
if numel(z)~=size(X,2)
error('mismatch in input sizes')
end
X2=mat2cell(X,ones(size(X,1),1),size(X,2));
z2=num2cell(z);z2=reshape(z2,size(X2));
X2=cellfun(@(data,sz) repelem(data,sz,1),X2,z2,'UniformOutput',false);
T=cell2mat(X2);
clc,disp(T)
Más respuestas (1)
Stephen23
el 30 de Abr. de 2020
Simpler, no data duplication, fewer intermediate variables with less memory footprint:
>> X = [2,1,2,10,3,0,0,0,0;2,2,3,20,5,0,0,0,0]
X =
2 1 2 10 3 0 0 0 0
2 2 3 20 5 0 0 0 0
>> z = [2,3];
>> fun = @(r,n) r*ones(1,n);
>> idx = cell2mat(arrayfun(fun,1:numel(z),z,'uni',0));
>> T = X(idx,:)
T =
2 1 2 10 3 0 0 0 0
2 1 2 10 3 0 0 0 0
2 2 3 20 5 0 0 0 0
2 2 3 20 5 0 0 0 0
2 2 3 20 5 0 0 0 0
4 comentarios
Rik
el 30 de Abr. de 2020
Thanks for your thorough reply.
It does seem a bit unfair to count X2 in the memory footprint, but not count arrayfun(fun,1:numel(z),z,'uni',0) (not that it is going to matter a lot), but I see what you mean now.
Stephen23
el 1 de Mayo de 2020
Editada: Stephen23
el 1 de Mayo de 2020
"It does seem a bit unfair to count X2 in the memory footprint, but not count arrayfun(fun,1:numel(z),z,'uni',0)..."
The intermediate cell array has 264 bytes for the original data, it scales with the size and contents of z.
Due to the transient nature of these intermediate arrays, and the unknown sequence in which the JIT compiler might create and destroy them, the only way to really know the actual memory consumption is to measure it: please feel free to do some tests and post the results here.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!