For Loop or function for repeating action
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
JacquelineK
am 13 Sep. 2017
Kommentiert: JacquelineK
am 21 Sep. 2017
I have A with 225 x 2 vectors. One Column is a variable always ranking from 1-5 (like grades) and the second is also numeric. I now want to calculate the mean, median, first and third quantile of the second vector, for each grade score.
The result I need, need to be interpreted like: mean(age) of A students better than mean(age) of B students
Grades 1 2 3 [etc]
Mean
Median
1st Qntl
3rd Qntl
I did it all by manually, which is kind of a lot, because I have 8 hypothesis for which the calculations are almost the same (the matrix A is in reality 225*11 but I only need 2-3 vectors per hypothesis). Now I wonder if there is a way to "do it faster and more efficient" namely in a for loop?
where I can write something like:
for i = 1:5
if ERM == i
mean_Hyp_1 = nanmean(A(ERM==1;:,2))
meadian_Hyp_1 = nanmedian(A(ERM==i;:,2)
etc
end
end
Thanks in advance
0 Kommentare
Akzeptierte Antwort
Vishwas
am 19 Sep. 2017
You had the right idea. "find" function can be used to find all the rows where ERM == 1,2,.. in a loop and the result can be calculated.
Let me show this via an example:
a = [1;3;2;4;5;1;2;4;3;5;3;2;1]
b = [10;15;24;54;36;57;87;98;65;78;05;48;65]
input = [a b]
mean = []
median = []
for i = 1:5
mean(i) = nanmean(input(find(input(:,1)==i), 2))
median(i) = nanmedian(input(find(input(:,1)==i), 2))
end
I the case above, we are using the "find" function on the first column of input, extracting the indices for all values of input(:,1) == i and finding the mean of all the values from the second column.
9 Kommentare
Stephen23
am 20 Sep. 2017
@Vishwas Vijaya Kumar: is there a good reason for shadowing the inbuilt input function?
Weitere Antworten (1)
Tim Berk
am 19 Sep. 2017
You can use the condition A(:,1) == i as indexing for which values in A(:,2) to consider, i.e.
A = [1 2 3 1 1 2 3; 4 5 6 7 8 9 0]'
for i = 1:3
mean_A(i) = nanmean(A(A(:,1)==i,2));
% etc..
end
1 Kommentar
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!