How to repeat a row by a certain factor

2 次查看(过去 30 天)
I have this sample matrix:
A=[2 2 2; 3 3 3; 4 4 4];
I would like to multiply each row by a certain factor (in this specific case, the first by 2, the second by 1, and the third by 3) to generate:
A_New= 2 2 2 2 2 2 3 3 3 4 4 4 4 4 4 4 4 4
Does anyone have suggestions on how to do this? I tried:
B = repmat(A,[2 1 3],1)
but this created separate matrices.

采纳的回答

Mohammad Abouali
Mohammad Abouali 2015-4-26
编辑:Mohammad Abouali 2015-4-26
% Creating sample data
A=[2 2 2; 3 3 3; 4 4 4];
nRep=[2,1,3];
% Constructing A_New as instructed.
A_new=cell2mat(arrayfun(@(r) repmat(A(r,:),1,nRep(r)), ...
1:numel(nRep), ...
'UniformOutput',false));
% printing the results
fprintf('A=');
fprintf('%d ',A_new)
fprintf('\n');
Once you run it you get this:
A=2 2 2 2 2 2 3 3 3 4 4 4 4 4 4 4 4 4
  1 个评论
Mohammad Abouali
Mohammad Abouali 2015-4-26
To preserve the structure then do this:
A=[2 2 2; 3 3 3; 4 4 4];
nRep=[2,1,3];
A_new=cell2mat( arrayfun(@(r) repmat(A(r,:),nRep(r),1),(1:numel(nRep))','UniformOutput',false) )
A_new =
2 2 2
2 2 2
3 3 3
4 4 4
4 4 4
4 4 4
If this is answering your question, please accept the answer by choosing the green button on top

请先登录,再进行评论。

更多回答(1 个)

Jessica
Jessica 2015-4-26
This is very helpful. Is there a way to preserve the structure so that it is in the format:
A_New=[2 2 2; 2 2 2; 3 3 3; 4 4 4; 4 4 4; 4 4 4];
Thanks!

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by