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

2 次查看(过去 30 天)
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