Sum of elements in 2D matrix greater tha 150
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sasidharan Subramani
el 12 de Dic. de 2020
Comentada: John D'Errico
el 14 de Dic. de 2020
I wouls like to find the sum of elements in a 2D matrix (254*318) with elements value greater than 150. but I get the code run but the answer is wrong if nayone could find the erro would be very helpful.R_10M is the name of the matrix
for a = 1:254
for b = 1:318
if (R_10M(a,b) > 150)
value = sum(sum(R_10(a,b)));
end
end
end
2 comentarios
dileesh pv
el 14 de Dic. de 2020
The loops in MATLAB is generally slow. MATLAB is pretty good with opearating on matrices. For a faster and efficient execution use the inherent strengths of MATLAB.
This can be done in a single step;
s = sum( R_10M (R_10M >150));
A detailed example code is given below;
R_10M = round(rand(254,318)*300); % Matrix with random entry
s = sum (R_10M (R_10M >150)); % Required sum
% Above line of code can be deconstructed into two steps as given below
a1= (R_10M >150); % Generate the logical array where the non-zero entries
% are at the indices of elements whose values are higher than 150
s1=sum(R_10M(a1)); % sum up the elements corresponding to the non-zero
% entries in the logical array a1
John D'Errico
el 14 de Dic. de 2020
@dileesh pv
Thank you for the explanations. I should have done that in my answer.
Respuesta aceptada
VBBV
el 12 de Dic. de 2020
Editada: VBBV
el 12 de Dic. de 2020
for a = 1:254
for b = 1:318
if (R_10M(a,b) > 150)
value(a,b) = R_10M(a,b); % use row and column indices for values matrix required before summing,
end
end
end
V = sum(sum(value)); % singular value
VV = sum(value); % vector of summed values
What you intend to sum of values > 150 in your matrix R_10, needs further specific conditions e.g. summing row wise or column wise ? or both (like you are doing inside if condition) ?
3 comentarios
Más respuestas (1)
John D'Errico
el 12 de Dic. de 2020
Editada: John D'Errico
el 12 de Dic. de 2020
Time to learn to use MATLAB as it is designed to be used.
value = sum(R_10M(R_10M > 150));
One line. No loops are necessary.
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices 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!