How to subtract elements in a matrix from each other

17 ビュー (過去 30 日間)
Colin Lynch
Colin Lynch 2018 年 6 月 5 日
編集済み: Stephen23 2018 年 6 月 6 日
Hello there!
I want to find out how I can subtract the elements of a matrix from one another in a particular order. Lets say that I have the following matrix:
matrix_1 = [30 39 42; 10 15 22; 1 5 7]
This matrix represents the running total counts of some function. To get the counts for each individual cell, I want to subtract the element in a cell from the one before it. In this case, the solution will do something like this:
matrix_2 = [30-22 39-30 42-39; 10-7 15-10 22-15; 1 5-1 7-5]
in order to produce:
matrix_3 = [8 9 12; 3 5 7; 1 4 2]
Does anyone know of a way I can automize this process so I don't need to calculate this by hand?
Thank you in advanced!
Sincerely,
Colin
  3 件のコメント
Colin Lynch
Colin Lynch 2018 年 6 月 6 日
The way I did this particular count is that it starts on the bottom left hand corner of the matrix (where matrix_one equals 1), then goes up sequentially to the right (where it equals 5), to the right again (where its 7) and then jumps up to the second row on the far left (where its 10) and so on. Does that make sense?
Stephen23
Stephen23 2018 年 6 月 6 日
編集済み: Stephen23 2018 年 6 月 6 日
@Colin Lynch: I believe 42-39=3.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 6 月 6 日
編集済み: Stephen23 2018 年 6 月 6 日
With some juggling of matrices this can be done with just one line of code:
>> A = [30 39 42; 10 15 22; 1 5 7]
A =
30 39 42
10 15 22
1 5 7
>> flipud(reshape([A(end,1),diff(reshape(flipud(A).',1,[]))],size(A,2),[]).')
ans =
8 9 3
3 5 7
1 4 2
The required order of data is very unusual: the flipud, reshape, and transpose operations are just to get the data into a simpler order (i.e. the order of linear indexing), which then makes calculating the difference easy with just one diff call.

その他の回答 (1 件)

KSSV
KSSV 2018 年 6 月 6 日
m1 = [30 39 42;
10 15 22;
1 5 7] ;
m2 = [30-22 39-30 42-39;
10-7 15-10 22-15;
1 5-1 7-5] ;
[m,n] = size(m1) ;
iwant = zeros(size(m1)) ;
iwant(:,2:end) = diff(m1')' ;
iwant(m,1) = m1(m,1) ;
for i = 1:m-1
iwant(i,1) = m1(i,1)-m1(i+1,n) ;
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by