Adding the first row of a matrix to every row

2 次查看(过去 30 天)
Hello,
Question asks to Create a matrix A of 'm'x'n' defined by: A(i,j)=ij+i if i is odd, and A(i,j)=i+jif i is even.
I've got that in the bag but there is a operation step that I'm not having any luck with. "Add the first row to every row other than the first row" My presumption was using the operation A(i,:) = A(i,:) - A(1,:) however the problem that I'm coming across is that testing any values of m and n above 2 would lead to only the last row being operated on. is that line of code inappropriate for the operation?
  1 个评论
Jan
Jan 2018-4-18
@amy wang: A confusing question.
Add the first row to every row
Sounds like a job for the operator "+", but you use "-".
testing any values of m and n above 2 would lead to only the
last row being operated on
It seems like there is a problem in your code, but you do not post it. Then guessing the reason is hard.
What is the relation between
A(i,j)=ij+i if i is odd, and A(i,j)=i+j if i is even
and
Add the first row to every other row
?

请先登录,再进行评论。

回答(2 个)

KSSV
KSSV 2018-4-18

Many methods are possible, one of the way:

A = rand(3,3) ;
iwant = A+A(1,:) ;  % Add first row to all the rows 
iwant(1,:) = A(1,:) ; % Replace the first row of result with first row of A

Jan
Jan 2018-4-18
A         = rand(3, 4);
A(2:3, :) = A(2:3, :) + A(1, :);   % Auto-expand since R2016b

For older versions:

A(2:3, :) = bsxfun(@plus, A(2:3, :), A(1, :));

Community Treasure Hunt

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

Start Hunting!

Translated by