Create new matrix based on grid location
1 次查看(过去 30 天)
显示 更早的评论
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
2 个评论
Jan
2021-2-13
Please post your code and a copy of the complete error message.
I do not see, how the output of the 4x4 matrix can be obtained based on the 10x3 input matrix and a "mean of the last column".
采纳的回答
Jan
2021-2-13
编辑:Jan
2021-2-13
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!