Trying to create a class that will adhere to a certain script and output:

I was given a certain script and output on my last homework: shown below, and I needed to create a class that made that script produce the output. I couldn't figure it out but I am still curious on how to do it because I spent hours trying to figure it out. Here is the info I was given and how far i got:
Create a Class called Number for use in the script below:
N = 4
numb(1)= Number(50);
numb(2)= Number(100);
numb(3) = Number(200);
numb(4) = Number(199);
numb(1).double;
numb(2).double;
numb(1).double;
numb(3).mystery(numb(1))
numb(4).mystery(numb(1))
for k= 1:N
fprintf('The value in Number %d is %d.\n', k, numb(k).value)
end
This should yield the following output:
The value in Number 1 is 200.
The value in Number 2 is 200.
The value in Number 3 is 40000.
The value in Number 4 is 399.
The Number Class should have a "value" property, and "double"
and "mystery" methods that act as follows:
The double method doubles the value stored in the Number.
The mystery method should take in a second Number. If the first Number is not prime,
then multiply the value of the first Number by the value stored in the second Number.
If the first Number is prime, then add the value of the second Number to the value stored
in the first Number.
Hint: consider using the "isprime" function in MATLAB.
How far I got:
classdef Number
properties
value
end
methods
function obj = Number(val)
obj.value = val;
end
function double(obj)
obj.value = 2 * obj.value;
end
function mystery(obj, other)
if isprime(obj.value)
obj.value = obj.value + other.value;
else
obj.value = obj.value * other.value;
end
end
end
end
which produced the following output:
N =
4
The value in Number 1 is 50.
The value in Number 2 is 100.
The value in Number 3 is 200.
The value in Number 4 is 199.

 Accepted Answer

Your class is a value class rather than a handle class. See this documentation page for a discussion of the difference. That means your double method:
function double(obj)
obj.value = 2 * obj.value;
end
sets the value property of the object that was passed into it to twice the previous value of that property then throws the modified copy of the object away (since it is not returned from the function.) The same holds for your mystery method; it doesn't change the original object.
You could make your class a handle class (as described on the page I linked above) or you could modify your methods to return the modified object and modify how they're called so they call the methods with an output argument.
BTW, double is not the best of names for your assignment to use for this method, as double already has a meaning in MATLAB and usually classes use it as a conversion method to convert themselves into double precision arrays.

More Answers (0)

Categories

Products

Release

R2021b

Community Treasure Hunt

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

Start Hunting!