Subtract column from previous column in for loop

4 ビュー (過去 30 日間)
Roisin Loughnane
Roisin Loughnane 2017 年 9 月 27 日
コメント済み: dpb 2017 年 9 月 28 日
I want to subtract previous column from columns, eg. column 2 - column 1 etc., and then divide by the difference (range) between the column values, per row of a large matrix.
For example I have matrix
A = [1 2 3; 4 5 6; 7 8 9]
I want to get matrix:
B = [0 1 1;0 1 1; 0 1 1]
and then divide by the range, which in this case is 0 but for me it won't be, and will be different for each row
I think I can use bsxfun, but am unsure how to use this in a loop, and using values from previous iteration in loop. I am very new to Matlab, and any help will be greatly appreciated.

採用された回答

dpb
dpb 2017 年 9 月 27 日
Presuming I infer your meaning precisely...
>> x=randi(200,4,3) % sample dummy data
x =
127 182 88
198 115 121
127 68 145
121 192 136
>> y=diff(x,[],2) % difference by column (note dummy placeholder for nth deriv)
y =
55 -94
-83 6
-59 77
71 -56
>> y=bsxfun(@mrdivide,y,range(y)) % compute difference/range(difference)
y =
0.3571 -0.5497
-0.5390 0.0351
-0.3831 0.4503
0.4610 -0.3275
>>
NB: In recent releases of Matlab, the above expansion using bsxfun will be done automagically simply by writing
y=y./range(y);
I'm limited to R2014b here which predates that syntax introduction...
  2 件のコメント
Roisin Loughnane
Roisin Loughnane 2017 年 9 月 27 日
Yes, that's exactly what I meant, thank you very much!!
Follow up question: now I end up with a matrix with one less column. How could I also wrap the command, so that column 1 becomes the difference between itself and the final column in the matrix ?
dpb
dpb 2017 年 9 月 28 日
Probably simplest is to just augment the matrix before you do the difference--
>> y=diff([x(:,end) x],[],2)
y =
39 55 -94
77 -83 6
-18 -59 77
-15 71 -56
>> y=bsxfun(@mrdivide,y,range(y))
y =
0.4105 0.3571 -0.5497
0.8105 -0.5390 0.0351
-0.1895 -0.3831 0.4503
-0.1579 0.4610 -0.3275
>>

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by