Subtract column from previous column in for loop
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Roisin Loughnane
el 27 de Sept. de 2017
Comentada: dpb
el 28 de Sept. de 2017
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.
0 comentarios
Respuesta aceptada
dpb
el 27 de Sept. de 2017
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 comentarios
dpb
el 28 de Sept. de 2017
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
>>
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!