Write a function that prompts the User for a positive integer n

8 visualizzazioni (ultimi 30 giorni)
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 Commento
Steven Lord
Steven Lord il 20 Dic 2019
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.

Accedi per commentare.

Risposte (1)

Udoi
Udoi il 22 Giu 2022
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 Commento
Adam Danz
Adam Danz il 22 Giu 2022
Modificato: Adam Danz il 22 Giu 2022
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)'

Accedi per commentare.

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by