MATLAB: Create new matrix based on grid location

gridlocation

Suppose I have matrix A:
A=[4 1 0.6;4 1 0.8; 1 4 0.5; 1 3 0.3; 3 2 0.1; 2 1 0.6; 2 4 0.5; 3 2 0.4; 1 1 0.3; 1 2 0.1]
Now, I want to find the mean value in the last column matrix A above and then created in the new matrix. So I want to generate the new matrix A as:
A =
0.6000 0 0 0
0 0.2500 0 0
0.6000 0 0 0.5000
0.3000 0.1000 0 0
Anyone, can help me? I've tried looping and if command, but i always get errors

Best Answer

A = [4 1 0.6; 4 1 0.8; 1 4 0.5; 1 3 0.3; 3 2 0.1; 2 1 0.6; ...
2 4 0.5; 3 2 0.4; 1 1 0.3; 1 2 0.1];
result = zeros(max(A(:,1)), max(A(:,2)));
for i = A(:, 1).'
for j = A(:, 2).'
index = (A(:,1) == i & A(:,2)==j);
if any(index)
result(i, j) = mean(A(index, 3));
end
end
end
% result =
% [0.3, 0.1, 0.3, 0.5; ...
% 0.6, 0, 0, 0.5; ...
% 0, 0.25, 0, 0; ...
% 0.7, 0, 0, 0]
This does not match your wanted output exactly:
A =
0.6000 0 0 0
0 0.2500 0 0
0.6000 0 0 0.5000
0.3000 0.1000 0 0
Problems of your code:
for i = A(:, 1)
This runs a loop with 1 iteration only, where i is the first column of A. Maybe you mean:
for i = A(:, 1).'
Same for the other loop.
Remember that the if command needs a scalar argument. Then:
if A(:,1) == i & A(:,2)==j
is modified internally to:
if all(A(:,1) == i & A(:,2)==j)
which is TRUE because i is the first column of A already (see above).
My code overwrites result(i,j) multiple times with the same value. It is just thought to clarify, what you want to obtain. For a real program you would use the faster:
result = accumarray(A(:, 1:2), A(:, 3), [], @mean)