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
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".
hello Jan, in matrix A above:
A =
4.0000 1.0000 0.6000
4.0000 1.0000 0.8000
1.0000 4.0000 0.5000
1.0000 3.0000 0.3000
3.0000 2.0000 0.1000
2.0000 1.0000 0.6000
2.0000 4.0000 0.5000
3.0000 2.0000 0.4000
1.0000 1.0000 0.3000
1.0000 2.0000 0.1000
I want create new matrix with 4x4 based on value of column 1 and 2, you can see that the values ranges from 1 to 4. In short, the column 1 as new row matrix and the column 2 as new column matrix.. the code as far as I'm trying:
result=zeros(length(unique(A(:,1))),length(unique(A(:,2))))
for i = A(:,1)
for j = A(:,2)
if A(:,1) == i & A(:,2)==j
result(i,j)=mean(A(:,3));
end
end
end
thx.

댓글을 달려면 로그인하십시오.

 채택된 답변

Jan
Jan 2021년 2월 13일
편집: Jan 2021년 2월 13일

0 개 추천

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)

댓글 수: 1

eko supriyadi
eko supriyadi 2021년 2월 13일
wonderful answer Jan, accumarray saves time faster than looping if command

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2021년 2월 13일

댓글:

2021년 2월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by