how to get following matrix using bsxfun

조회 수: 1 (최근 30일)
Ace_ventura
Ace_ventura 2015년 2월 7일
댓글: Geoff Hayes 2015년 2월 8일
I have a matrix x=[0 0 0;5 8 0; 7 6 0].
I want a matrix m=[0 0 0; 5 8 0 ; 7 6 0 ; 0 0 8; 5 8 8; 7 6 8; 0 0 16; 5 8 16; 7 6 16] I want that the third column of matrix x gets multiplied each time by 8 while other two columns remain same. I want this to continue until the value in third column reaches 72. how can i do it with bsxfun??

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 2월 7일
Saurabh - if x is your defined as
x=[0 0 0;5 8 0; 7 6 0];
then you could replicate it 10 times as
m = repmat(x,10,1);
then just replace the third column with
m(:,3) = cell2mat(arrayfun(@(u)repmat(u*8,3,1),0:9,'UniformOutput',false)');
to produce the desired result. Try the above and see what happens!
  댓글 수: 3
Ace_ventura
Ace_ventura 2015년 2월 7일
편집: Ace_ventura 2015년 2월 7일
can it be done using bsxfun?? And what if i wanted to add certain constant to 1 and 2 column as well continuously throughout. Say addition of 5 throughout entire columnn1 and addition of 9 throughout entire column 2 with each repetition of matrix. Thanks in advance:)
Geoff Hayes
Geoff Hayes 2015년 2월 8일
Saurabh - try the following
x=[0 0 0;5 8 0; 7 6 0];
cell2mat(arrayfun(@(u)x + repmat([u*5 u*9 u*8],3,1),0:9, 'UniformOutput',false)')
5, 9, and 8 are added to columns 1, 2, and 3 respectively of each new matrix. We use repmat to create the matrix to add to x at each iteration u. We apply this add using arrayfun for iterations 0 through 9. The result is a cell array, so we transpose the output from arrayfun and convert to a matrix using cell2mat.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2015년 2월 7일
편집: Andrei Bobrov 2015년 2월 7일
k = 0:72/8;
M = repmat(x,numel(k),1);
add = 8*ones(size(x,1),1)*k;
M(:,3) = add(:);
with bsxfun
m = reshape(bsxfun(@plus,permute(x,[1 3 2]),...
bsxfun(@times,reshape([0 0 1],1,1,[]),0:72/8)),[],3);
  댓글 수: 1
Ace_ventura
Ace_ventura 2015년 2월 8일
Thanks Andrei..Could u also answer my second question. what if i wanted to add a constant to column 1 and column2 with each matrix repetition. That is to say,if my constant to be added is 5 ,then my first column in second repetition of matrix is 5 10 12 and second column becomes 5 13 11. In third repetition first column becomes 10 15 17 and second column becomes 10 18 16 and so on. During this entire process my third column goes on with addition of 8 each time ( as u have answered)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by