I am trying to solve this ques but I am getting some trouble. Write a custom function with the declaration: PPTask1p2_f(N) and save it in a file named PPTask1p2_f.m.The function loops through the values from 1 to N and for each number n it should dis

조회 수: 2 (최근 30일)
Write a custom function with the declaration: PPTask1p2_f(N) and save it in a file named PPTask1p2_f.m.The function loops through the values from 1 to N and for each number n it should display in the command window: ‘n is divisible by 3’ (use disp function), ‘n is divisible by 5’, ‘n is divisible by 3 AND 5’, or ‘n is NOT divisible by 3 or 5’. You must use a for loop, the function rem to figure out if a number is divisible by 3 or 5, and num2str to convert each number to a string for displaying. You can use any combination of if, else, and elseif. Call the function in the command window: PPTask1p2_f(25) and verify if the following information is displayed: >> PPTask1p2_f(25) 1 is NOT divisible by 3 or 5 2 is NOT divisible by 3 or 5 3 is divisible by 3 4 is NOT divisible by 3 or 5 5 is divisible by 5 6 is divisible by 3 7 is NOT divisible by 3 or 5 8 is NOT divisible by 3 or 5 9 is divisible by 3 10 is divisible by 5 11 is NOT divisible by 3 or 5 12 is divisible by 3 13 is NOT divisible by 3 or 5 14 is NOT divisible by 3 or 5 15 is divisible by 3 AND 5 16 is NOT divisible by 3 or 5 17 is NOT divisible by 3 or 5 18 is divisible by 3 19 is NOT divisible by 3 or 5 20 is divisible by 5 21 is divisible by 3 22 is NOT divisible by 3 or 5 23 is NOT divisible by 3 or 5 24 is divisible by 3 25 is divisible by 5
function PPTask1p2_f(n)
for i=1:1:n
x=rem(i,3)
if x>=1
disp('n is not devisable by 3 or 5')
elseif x==0
disp('n is devisable by 3')
end
end
  댓글 수: 1
matquest
matquest 2020년 4월 9일
What trouble are you having with the function? You have only posted the homework question and a code snippet. What is your approach to solving the problem?

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

채택된 답변

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi 2020년 4월 13일
Hello,
Firstly, use the rem function to get the remainders of every value of 'i' with 3 & 5 -
r3 = rem(i,3);
r5 = rem(i,5);
Next, use if-else loops to work with different possible scenarios. Use logical operators to get desired outputs -
if ~(r3 || r5)
disp([num2str(i),' is divisible by 3 AND 5']);
elseif (r3 && r5)
disp([num2str(i),' is NOT divisible by 3 or 5']);
else
if ~r3
disp([num2str(i),' is divisible by 3']);
else
disp([num2str(i),' is divisible by 5']);
end
end
References:
  • if-else-elseif statements: Link
  • disp function: Link
  • Logical operators: Link
Finally, MATLAB Onramp courses are a great way to begin learning MATLAB fundamentals. Find link here.
Hope this helps!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by