Sum of elements in 2D matrix greater tha 150
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
dileesh pv
2020-12-14
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
2020-12-14
@dileesh pv
Thank you for the explanations. I should have done that in my answer.
采纳的回答
VBBV
2020-12-12
编辑:VBBV
2020-12-12
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 个评论
更多回答(1 个)
John D'Errico
2020-12-12
编辑:John D'Errico
2020-12-12
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!