How to find the median of one part of a column being in a while loop?

조회 수: 3 (최근 30일)
saravan1992
saravan1992 2015년 9월 16일
편집: Thorsten 2015년 9월 16일
Hello, I have the following problem: I have one matrix in which I want the output to be presented and which looks like this:
A1=[1950 0;1951 0;1952 0;1953 0;1954 0;1955 0];
There is also this second matrix which contains my input:
A2=[1960 1;1961 2;1962 3;1963 4;1950 5;1951 6;1952 7;1950 8;1950 9;1952 10;1951 11;1952 12];
In the second column of A1 I want to print the median of the second column of A2 for each year. That is I want to print in A1(1,2) the median of A2(5,2),A2(8,2) and A2(9,2).
This is the code I have written and I know it is wrong I just can't figure the correct approach out.
A1=[1950 0;1951 0;1952 0;1953 0;1954 0;1955 0];
A2=[1960 1;1961 2;1962 3;1963 4;1950 5;1951 6;1952 7;1950 8;1950 9;1952 10;1951 11;1952 12];
Year=1950;
for k=1:1:12;
for l=1:1:6;
while A2(k,1)==Year;
A1(l,2)=median(A2(k,2));
Year=Year+1;
end
end
end
Thanks!

답변 (2개)

Nobel Mondal
Nobel Mondal 2015년 9월 16일
Is this what you're looking for?
A1=[1950 0;1951 0;1952 0;1953 0;1954 0;1955 0];
A2=[1960 1;1961 2;1962 3;1963 4;1950 5;1951 6;1952 7;1950 8;1950 9;1952 10;1951 11;1952 12];
thisYear = 1950;
thisRow = 1;
while (thisYear < 1956)
temp = find(A2(:,1) == thisYear);
if ~isempty(temp)
A1(thisRow,2) = median(A2(temp,2));
end
thisYear = thisYear + 1;
thisRow = thisRow + 1;
end
  댓글 수: 1
saravan1992
saravan1992 2015년 9월 16일
It works but unfortunately I am not even aware of what the temp structure is about. So I will first search and study a bit about it before using the code you proposed.
Thank you very much though!

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


Thorsten
Thorsten 2015년 9월 16일
편집: Thorsten 2015년 9월 16일
A solution without a while loop; if now values are given for the year, NaN is assigned:
for i = 1:size(A1,1)
A1(i,2) = median(A2(A2(:,1) == A1(i,1),2));
end
The expression
A2(:,1) == A1(i,1)
are the logical indices of those rows in A2 that have the matching year (given by A1(i,1)) in the first column.

카테고리

Help CenterFile Exchange에서 Interpolation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by