Calculating the sum of A elements which are numbers between 30 and 65

조회 수: 3 (최근 30일)
Hey, i need help with school assignment, i have created an array of 8 rows and 20 columns whose elements are random numbers between 10 and 100:
A=randi([10,100],8,20);
i have to find the elements in A which are between 30 and 65! and Calculate the sum of these numbers.
this is what i got so far:
A=randi([10,100],8,20);
for i=1:8
for j=1:20
if A(i,j)>30 & A(i,j)<65
sum A(i,j)
end
end
end
And this only shows the first if argument, and the sum is 401 which i think is the sum if hiw many numbers are greater than 30.
Now my teacher says we have to use this format which i dont understand why:
s=0;
N=0;
for i=1:8
for j=1:20
if...

채택된 답변

David Hill
David Hill 2019년 11월 7일
You had it!
A=randi([10,100],8,20);
B=0;
for i=1:8
for j=1:20
if A(i,j)>30 && A(i,j)<65
B=B+A(i,j);%B is the sum of all elements of A between 30 and 65
end
end
end
  댓글 수: 1
Karem Kassem
Karem Kassem 2019년 11월 7일
Thanks Man ! Do you have any idea why i have to put s = 0 N = 0 in the beginning?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

jannat alsaidi
jannat alsaidi 2019년 11월 7일
No need to initiate two values s and N, only one for accumulator.

카테고리

Help CenterFile Exchange에서 Encryption / Cryptography에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by