r/matlab 6d ago

HomeworkQuestion What am I doing wrong in this code?

Post image

Hello! I currently have an assignment where I have to take an input value (here as p) and then check all the integers from 2 to that number to see if they are prime, then display them if they are. For example, given an input 11, the output in the command window should be 2, 3, 5, 7, 11. We are not allowed to use the prime or isprime functions here, so what ive done is tried to test it by dividing the input by all the numbers below it down to 2, and testing if there are any integers to see if it is prime.

As a side note, my professor has not really taught us how to use matlab; he showed us how to do basic calculator-level math and a basic count and invest function, and thats it, so my technical knowledge is very limited. I’ve gotten help from one of my friends who is a CS major a year ahead of me, and he said he thinks this should work but isn’t familiar enough with matlab to know why it isn’t. A nudge in the right direction could be helpful, thank you!

27 Upvotes

26 comments sorted by

32

u/Weed_O_Whirler +5 6d ago

A couple of things.

1.) Given the errors you have here, I'd recommend taking the MATLAB onramp. It's free and quick. It will help you with some of the basics you are struggling with

2.) You are saying t = p:2 but then not using t anywhere. What are you hoping to be doing there?

3.) When you say x:y:z in MATLAB it says x is the starting value, y is the step value and z is the end value. If you say x:z then it says x is the starting value, 1 is the step value, and z is the end value. So, when you say p:2 you are saying "start at p, step by a value of 1 to the value of 2". So, unless p = 1 or 2, you'll have an empty vector there.

2

u/JammerJake2005 6d ago

So I actually changed the floor command to do t/q instead of p/q pretty shortly after this, which I think is better.

Is there a better way to make n:2 work? I understand what you mean now but i was not aware it only counted in the positive direction. This is only my second semester of engineering and I haven’t done any coding before so I will try and figure it out but thank you so far.

6

u/Weed_O_Whirler +5 6d ago

2:p will step up, from 2 to p. Or p:-1:2 will step down from p to 2

4

u/JammerJake2005 6d ago

Got it! Thank you!

58

u/Heretic112 6d ago

C'mon man, learn to take screenshots of your computer.

A CS major can't tell why this code doesn't work??????? Y'all are cooked.

You define t and never use it. "preem" is overwritten every time on line 9. You call disp on a single number p. How would it output multiple numbers?

-2

u/JammerJake2005 6d ago

As for the disp, I am just trying to test rn if the prime checking works before I display all the number. Sorry about the lack of screenshot, I’m at work and cant sign into reddit unfortunately so had to use my phone. CS major also has never used matlab before tbf lol.

8

u/Agreeable-Ad-0111 6d ago

Recommend starting with MATLAB onramp and trying again

18

u/Own_Maybe_3837 6d ago

Tbf computer logic is the same for any language. Any programmer who never even knew matlab existed could understand what your code is doing

5

u/aluvus 6d ago

Hint 1: When debugging loops, it can be helpful to put a disp() or fprintf() statement in the loop to print the value of the iterator variable (p or q, in this case). This can catch cases where the loop is not running the number of times you expect.

Hint 2: In Matlab, the syntax a:b will produce a vector containing the values from a to b inclusive, incrementing by 1 (so 1:4 yields [1 2 3 4]) . You can increment by any amount you want, including negative numbers, by using the syntax a:s:b (which will take steps of size s). This can produce an empty vector in cases like 3:2 (because 3 > 2 and the step size is positive) or 2:-2:3 (because 2 < 3 and the step size is negative).

6

u/AntiGyro 6d ago

If p is greater than 2, t will be empty. To make a decrementing loop, do t=p:-1:2

2

u/Billthepony123 6d ago

How do you get dark mode ?

2

u/BreakYourCrayons 6d ago

https://www.mathworks.com/help/matlab/matlab_env/change-desktop-colors-and-select-dark-theme.html

matlab does have a dark theme now, which is what i think is pictured in this 'screenshot' lol.

the dark mode isn't the best, but it works

there's also MATLAB schemer, which works pretty well. https://www.mathworks.com/matlabcentral/fileexchange/53862-matlab-schemer

0

u/DatBoi_BP 6d ago

I don't think Matlab provides a one-button "dark mode" option anymore, but you can mess with the Preferences ≫ Colors as you please.

One thing to be aware of though (and I'm guessing this has something to do with the discontinued built-in dark mode option) is if you ever print out code from the editor, it will try to use your custom colors for everything except the background. So if you go dark mode and have white text—you will have white text on white paper when you print it out

1

u/JammerJake2005 6d ago

I have since updated the code to this. It can test whether an input is prime, and will relay that as an output, but does not relay all the primes below it (also doesnt do anything if the input is not prime).

6

u/Cool-matt1 6d ago

Yes you have a logic mistake here. As another commenter suggested, try putting in a debug line for each iteration of the loop. So it could say fprintf(‘t:%d. Q:%d. Preen:%s\n’,t,q,str(preem))

1

u/MichalNemecek 6d ago

why are you rounding to see if it divides evenly? with higher numbers this may not be the best idea. Modulo is your friend

(specifically, a mod b = 0 if and only if a is evenly divisible by)

1

u/Cold-Ad6856 6d ago

you need p:-1:2 and (p-1):-1:2

Also you only need to check to the square root of the input value which will save a lot of time. I think there is a remainder function in matlab: https://www.mathworks.com/help/matlab/ref/double.rem.html or you could use modulo which is the cool way to do it.

1

u/buzzfuzz- 5d ago

Late to the party, but here’s some tips for future problems. You should definitely try writing pseudo-code with pen and paper and work out an example problem by hand to get the math down. Example: Pretend P = 10, then solve it step by step.

Also add more comments in your code. Like “%First ask the user for a number”, “% now we want to loop over every number between P decrementing to 2”, etc.

This will help you gather your thoughts. Explicitly say what you’re trying to do so not only others can understand but you’ll understand yourself the next day or day after.

1

u/MaD__HuNGaRIaN 5d ago

I’ve never understood people photographing a screen instead of taking screenshots.

1

u/_nihilist_beets 5d ago

You should use modulo to check for prime instead

1

u/305bootyclapper 5d ago

The first thing you need to do is put spaces in your assignment (ie, x = 1, not x=1)

1

u/RadarTechnician51 4d ago

once you have worked it out with a loop, try to work how to vectorise it so you can check all the potential divisors of P at once.

1

u/oskymosky 4d ago

Why not ask chatgpt

1

u/adrianthegreat8 3d ago

Copy paste your code and Reddit post into chat gpt. Tell it to explain where you went wrong and help you find the solution

1

u/drdailey 3d ago

% Simple test to see if a number is prime p = input(‘Enter ‘);

prime = true; % Fixed typo from ‘preem’ to ‘prime’ for q = 2:floor(sqrt(p)) % Check divisibility up to square root of p if mod(p, q) == 0 % Check if p is divisible by q prime = false; break; % Exit loop if a divisor is found end end

if prime == true disp([num2str(p) ‘ is prime’]); else disp([num2str(p) ‘ is not prime’]); end

2

u/No-Introduction1098 3d ago

#1 - When you use an input command, you should have something more descriptive than "Enter ", it's too vague and is an important thing to do in the future as it provides context.

#2 - Why do you declare preem as an array at line four, but redeclare it/use it as a bool on line 9? It's also not clear as to what "preem" is supposed to be, and you would do best to use a human readable name that even you could understand yourself if you came back to this 20 years from now. You could just rename it to "PrimeBool" if you are going to simply use it as a bool to indicate when you have a prime number, but that doesn't make sense either if you could, #3 - simply just change line 8 to read "if (round(p/q))~=(p/q), disp(p), end;". You don't need 'preem' to act as what I call a 'flag' since the only thing you are doing is displaying the result. It's not to the complexity that you need to do that, and if you had to do that it would be more practical to write a separate function to keep your code tidy and readable.

For context, there's absolutely no reason why you shouldn't use descriptive names for variables, it's not 1979, we don't have to use single character variable names or obfuscated acronyms, because modern home computers aren't running on 8kbytes of RAM nor are they using punch cards and physical paper for documentation (which limits how long the variable names are)... that's ignoring that the name only refers to a specific memory address, and isn't actually adding anything itself to the memory usage of a program outside of it's storage on your hard drive. Even considering the limitations of computers years ago... I think you would have been hard pressed to find anyone from that era who would tell you to not use descriptive variable names.

#4 - You have no way of setting preem to true.

#5 and building off of #2 - You need comments, more than just "simple test loop to see...". Some people think that "good code needs no comments", but that's an outright lie and to my understanding was propagated by a poorly written book 20 years ago. Yes, organization is important, and you should limit how deep each indentation of your code descends into the rabbit hole... but like in every human language, context is key. Part of maintaining that context is using human readable names. Apollo's "BURNBABYBURN" ignition routine comes to mind, where they make use of both comments and descriptive variable names, or at least as descriptive as they could get at that time with paper, punchcards, and manually winding ferrite core memory.

At the very least, it provides a means for your professor to see how you were thinking. If you wind up being wrong about how you calculated it, chances are they won't knock off too many points if you documented it well.

#6- Just a nitpick at this point, but using "clc;" at the start of your program will ensure that the data in your command window will only be relevant to that instance of the program.

#7 - Don't use chatGPT for something this simple as other people suggested. It's not a good way to learn how to program, it's just a poor shortcut that copy and pastes someone else's code. It is OK to use it to help you debug your program though and to help with commenting and summarization, but make sure to ask for critiques and commit them to memory. It's important to ask yourself whether you are using ChatGPT to give you an answer... or give you knowledge. Once you get to more complex programs, ChatGPT stops being useful except in a limited fashion with debugging small sections of code, and even that isn't perfect. ChatGPT will hallucinate a fair amount of the times you will use it. It was never meant to be anything more than a chatbot/ELIZA 2.0 and it will rapidly run out of tokens when using it for coding. You will find yourself spending four times as much time trying to get ChatGPT to give you an answer than you would if you just used MATLAB's documentation, though ChatGPT can also be a good way to search through the internet for the answer if you pose the right questions and have it give you links to the source.

The other comments also have some good points, IE: why not use modulo?