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
Rik 2020-4-30
How do you determine what values should be changed?
Philipp
Philipp 2020-4-30
It is a beam divided in 5 Elements, so 6 nodes. X is created by input data and z also, so 10 and 20 is the outer diameter and 3 and 5 the inner diameter.
The first Element before is X(1,:) and it should be divided by z(1) and the second Element is X(2,:) and should be divided by z(2)
Is this the answer to your question?
Thanks,
Philipp

请先登录,再进行评论。

采纳的回答

Rik
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
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
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
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by