Write a function that prompts the User for a positive integer n
8 ビュー (過去 30 日間)
古いコメントを表示
Write a function that prompts the User for a positive integer n.
İf n positive integer, the function outputs an n-by-n matrix, whose (i, j)th elements is ixj
But, İf n is not a positive integer, it does not output anything, instead, it prints "must be positive integer" on the screen and asks for a New input again
1 件のコメント
Steven Lord
2019 年 12 月 20 日
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
回答 (1 件)
Udoi
2022 年 6 月 22 日
We can use a simple if-else conditional check in MATLAB to implement the scenario described.
At first,we take the input value of n from the user using prompt,
We then apply an if-else conditional check,i.e if n is greater than 0,or n is a positive integer,we create a matrix with dimensions n*n where the value of each cell is i*j(row number*column number)
Wherease,if n is less than zero,we display "Must be a positive integer"
Code snippet:
prompt="Enter the value of n";
n=input(prompt);
if(n>0)
a=zeros(n,n);
for i=1:n
for j=1:n
a(i,j)=i*j;
end
end
disp(a);
elseif(n<=0)
disp("Must be a positive integer");
end
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial.
Folow the link (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
1 件のコメント
Adam Danz
2022 年 6 月 22 日
編集済み: Adam Danz
2022 年 6 月 22 日
Good start. Here are some suggestions
- The condition that tests n>0 should also include a test that n is an integer: rem(n,1)==0.
- The whole thing could be wrapped into a while-loop that continually prompts the users until they enter a positive integer.
- The two for-loops can be replaced with the following:
n = 5;
a = (1:n).*(1:n)'
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!