How do I apply a function to each cell in a matrix which is dependent on surrounding cells?

3 views (last 30 days)
For instance: I have a matrix
A = [1 2 1; 2 3 2; 4 1 2]
I need to write a function presumably using arrayfun that will create a new matrix (same dimensions)
Ignoring Matlab syntax I would imagine the function to look like this :
xy2 = (.25*x(n-1)y + .5*xy1 + .25*x(n+1)y)
The function would create a new value in the same position in a new matrix that would take into account values that occurred before and after the cell at hand.
Thank you in advance for the help!
  3 Comments
Athena Jones
Athena Jones on 7 Jun 2016
A is used as the production of a commodity y values are by year and x values vary by preservative used to treat the commodity. A2 is hypothetically the disposal of the commodity

Sign in to comment.

Answers (1)

per isakson
per isakson on 7 Jun 2016
My guess:
A = [1 2 1; 2 3 2; 4 1 2];
%%xy2 = (.25*x(n-1)y + .5*xy1 + .25*x(n+1)y)
B = cat( 2, zeros(size(A,1),1), A, zeros(size(A,1),1) );
C = arrayfun( @(n) (B(:,n-1)/4 + B(:,n)/2 + B(:,n+1)/4), [2,3,4], 'uni',false );
D = cell2mat(C);
A2 = [1 1.5 1; 1.75 2.5 1.75; 2.25 2 1.25];
if all(all(D==A2))
disp('Success')
else
disp('Failure')
end
which returns
Success

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!