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

1 回表示 (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by