Operating on One Column Based on Another
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jeremy
el 27 de Abr. de 2018
Comentada: Jeremy
el 28 de Abr. de 2018
So I've run into a buzzsaw of a problem. I have a m x n numeric matrix (no strings, etc.) and two columns are of interest. Column 1 looks like this:
A = [1;1;1;1;2;2;2;3;3;3;3;3;4;4;4;5;5;5]
Next, column 2:
B = [1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18];
What want to do is look at where values of A are equal and operate on those values in the same position in B. In other words, A(1:4) = 1 so I want to add together (or standard deviation, variance, etc.) B(1:4). Then, I want to move on to the next set of equal values of A and operate on the corresponding positions of B, and so on. Once values have been added together, I want to compare the result against a tolerance value and if the sum falls outside of the value, I want to delete those rows.
The problem I'm running into is that all of the comparison methods I've tried automatically dismiss the last value in B. So, where A(5:1) doesn't equal A(4:1), I'll get a sum, let's say, for B(1:3) instead of B(1:4). For example, one method I tried was:
a = unique(matrix(:,col_A))
tol = 5;
for i = 1:length(matrix)
idx = find(matrix(i,col_A) == a);
if isequal(matrix(i),idx)
std_dev = std(matrix(m,B));
if std_dev < tol
matrix(matrix(m,:)) = [];
end
end
end
At first, because of how isequal works, the algorithm discards A(4,1) doesn't equal A(5,1). I understand why this is happening, but I can't think of a viable solution. I tweaked it a bit, but now when I run the algorithm as written above, nothing happens at all.
If I was unclear at any point, don't hesitate to let me know. Any help you all can provide would be most appreciated!
0 comentarios
Respuesta aceptada
Stephen23
el 27 de Abr. de 2018
Editada: Stephen23
el 27 de Abr. de 2018
>> A = [1;1;1;1;2;2;2;3;3;3;3;3;4;4;4;5;5;5];
>> B = [1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18];
>> S = accumarray(A,B,[],@sum)
S =
10
18
50
42
51
>> S(A)
ans =
10
10
10
10
18
18
18
50
50
50
50
50
42
42
42
51
51
51
If the values of A are not consecutive integers starting from one, then use unique first and use its third output argument.
Más respuestas (0)
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!