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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by