Trying to create a class that will adhere to a certain script and output:
Show older comments
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
More Answers (0)
Categories
Find more on Create System Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!