Sum of elements in 2D matrix greater tha 150

2 visualizaciones (últimos 30 días)
Sasidharan Subramani
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
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
This is exactly what John D'Errico has suggested. I just added little detailed explanation to it.
John D'Errico
John D'Errico el 14 de Dic. de 2020
@dileesh pv
Thank you for the explanations. I should have done that in my answer.

Iniciar sesión para comentar.

Respuesta aceptada

VBBV
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
VBBV
VBBV el 12 de Dic. de 2020
Ok. Did you get any error after changing to R_10M ?
Sasidharan Subramani
Sasidharan Subramani el 13 de Dic. de 2020
yes, got it thank you.

Iniciar sesión para comentar.

Más respuestas (1)

John D'Errico
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.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by