Creating a Matrix with for loop
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Rik
2020-4-30
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)
更多回答(1 个)
Stephen23
2020-4-30
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 个评论
Rik
2020-4-30
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
2020-5-1
编辑:Stephen23
2020-5-1
"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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!