MATLAB: Selecting to do operation on every fourth row

MATLABmatrixoptimization

this quetion might sound confusing
i have the 840 rows of the following is a sample
f(:,1) f(:,2) f(:,3)
air 0.693 0.329 0.013
train 0.109 0.203 0.168
bus 0.356 0.153 0.250
car 0.010 0.076 0.193
this the previous function i had which was easy
fun = @(x)[(((1+x(4))*(x(1)*f(:,1) + x(2)*f(:,2) + x(3)*f(:,3))) + (x(4)*((f(:,1).^x(1)).*(f(:,2).^x(2)).*(f(:,3).^x(3)))) + ep - en - u);
the question i like to code the following for all the my data. i want to do the following opation on every 4 rows grouped togther
to explain further
x(1)*((column1,row1) - (column1,row2))+ x(2)*((column2,row1)-(column2,row2))+ x(3)*((column3,row1)-(column3,row2))
x(1)*((column1,row1) - (column1,row3))+ x(2)*((column2,row1)-(column2,row3))+ x(3)*((column3,row1)-(column3,row3))
x(1)*((column1,row1) - (column1,row4))+ x(2)*((column2,row1)-(column2,row4))+ x(3)*((column3,row1)-(column3,row4))
i am basically taking the first row minus the other rows in each column
this will repeat for the set of 4 untill i get to the end of 840 enteries
i hope someone can help

Best Answer

Hi,
As per my understanding you want to consider every 4 rows as 1 set , apply your formula and repeat this till the last row. You can use a vector as index with increments of 4 and define the logic (for formula) using this index” accordingly. Here is a sample code:
f = randi(5,[840 3]); % Consider random array of size 840 x 3
y = zeros(840,1); % Array to store output
i= 1: 4: 840; % Index
y(i) = (f(i,1) - f(i+1,1)) + (f(i,2) - f(i+1,2)) + (f(i,3) - f(i+1,3));
y(i+1) = (f(i,1) - f(i+2,1)) + (f(i,2) - f(i+2,2)) + (f(i,3) - f(i+2,3));
y(i+2) = (f(i,1) - f(i+3,1)) + (f(i,2) - f(i+3,2)) + (f(i,3) - f(i+3,3));
y(i+3) = NaN; % Ignore