Creating a Matrix with for loop
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Rik
il 30 Apr 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)
Più risposte (1)
Stephen23
il 30 Apr 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 Commenti
Rik
il 30 Apr 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
il 1 Mag 2020
Modificato: Stephen23
il 1 Mag 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.
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!