How to let the user put matrix not single element and divisible each element in that matrix

1 回表示 (過去 30 日間)
Make function called somthing(x) that loops through the vector x and for each number n in vector x it should display ‘n is divisible by 2’, ‘n is divisible by 3’, ‘n is divisible by 2 AND 3’ or ‘n is NOT divisible by 2 or 3’. Use a for loop, the function mod or rem to figure out if a number is divisible by 2 or 3, You can use any combination of if, else, and elseif. this is homework, i tried this code but
function[out]=divisible_m(x)
x=input('Enter any Vector')
if (rem(x,2)==0&&rem(x,3)==0)
disp('divisible on 2 and 3')
elseif (rem(x,2)==0&&rem(x,3)~=0)
disp('divisible on 2')
elseif (rem(x,2)~=0&&rem(x,3)==0)
disp('divisible on 3')
else
disp('not divisible ')
end
end
this code let user to enter just 1 element and my question is how to let the user put matrix not single element and divisible each element in that matrix

採用された回答

Bob Thompson
Bob Thompson 2018 年 7 月 26 日
"Make function called somthing(x) that loops through the vector x and for each number ..." Your code does not currently have a loop within it, which is why it only works for single values. Because the prompt says, "for each number" a for loop is probably a good place to start.
Because you know that the code works for single values, then it means your conditional checks are most likely correct, which is the complex part of the problem. input() is able to receive any size matrix, whether 1x1 for single values, or MxN for more complex inputs. This means the input line most likely doesn't need to be changed.
The only thing left to do then is to create a loop so that the conditions are checked for each number.
  1 件のコメント
sami alzeq
sami alzeq 2018 年 7 月 30 日
thank you it's finally working
function[out]=divisible_m(x)
x=input('Enter any Vector = ')
for n=1:1:length(x);
x(n)
if (rem(x(n),2)==0&&rem(x(n),3)==0)
disp('divisible on 2 and 3')
elseif (rem(x(n),2)==0&&rem(x(n),3)~=0)
disp('divisible on 2')
elseif (rem(x(n),2)~=0&&rem(x(n),3)==0)
disp('divisible on 3')
else
disp('not divisible')
end
end
end

サインインしてコメントする。

その他の回答 (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