Create new matrix based on grid location
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Jan
le 13 Fév 2021
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".
Réponse acceptée
Jan
le 13 Fév 2021
Modifié(e) : Jan
le 13 Fév 2021
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)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!