Adding the first row of a matrix to every row

2 Ansichten (letzte 30 Tage)
amy wang
amy wang am 18 Apr. 2018
Beantwortet: Jan am 18 Apr. 2018
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 Kommentar
Jan
Jan am 18 Apr. 2018
@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
?

Melden Sie sich an, um zu kommentieren.

Antworten (2)

KSSV
KSSV am 18 Apr. 2018

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 am 18 Apr. 2018
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