Performing operations on row elements in a matrix

조회 수: 104 (최근 30일)
Stewart Tan
Stewart Tan 2019년 8월 13일
댓글: Guillaume 2019년 8월 21일
So I'm creating some simple examples on trying to perform operations between rows in a matrix such as division. I have a matrix where:
my_mat = [2 4 6 8; 4 8 12 16]
which looks like so when printed.
my_mat =
2 4 6 8
4 8 12 16
and what I'm trying to do now is to divide the elements of the first row with the corresponding neighbouring ones which is the second row in this case since it's only a 2x4 matrix. This means 2/4, 4/8, 6/12 and 8/16
Then perhaps printing out the result as the output
0.5
0.5
0.5
0.5
How do i perform row operations in a single matrix?
I've looked into bsxfun but apparently i can't figure out the way to perform row operations with it.
  댓글 수: 1
Guillaume
Guillaume 2019년 8월 21일
Adam has answered your question, I just want to comment on one aspect of your question. Why do you show the desired output as a column when you started with rows? One important aspect of writing good code is consistency. Changing the direction of vectors willy-nilly certainly isn't consistent.
It can also have huge impact on your result, consider (assuming R2016b or later:)
A = [1, 2, 3, 4] + [5, 6, 7, 8] %addition of a row vector with a row vector
B = [1, 2, 3, 4] + [5; 6; 7; 8] %addition of a row vector with a column vector

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

답변 (1개)

Adam Danz
Adam Danz 2019년 8월 13일
편집: Adam Danz 2019년 8월 21일
To divide the elements of two row, use " ./ "
row1 ./ row2
If you're working with a matrix and want to divide row n by row n+1, element-wise,
my_mat = randi(6,4); %fake data
result = my_mat(1:end-1,:) ./ my_mat(2:end,:)

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by