Write a function that prompts the User for a positive integer n
조회 수: 12 (최근 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!