Performing operations on row elements in a matrix

106 views (last 30 days)
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 Comment
Guillaume
Guillaume on 21 Aug 2019
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

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 13 Aug 2019
Edited: Adam Danz on 21 Aug 2019
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,:)

Community Treasure Hunt

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

Start Hunting!