Matlab parsing error after class declaration
12 views (last 30 days)
Show older comments
This is my first time writing in matlab, but I've written in other languages. I can't seem to figure out what is causing the parsing error in this section of code. I'm trying to make a class of a popular simulation where if there's an equally likely chance of something moving in any direction, on average how far does it get away after x steps. I'm just trying to make the function "step" change the property "position" correctly depending on what the random integer is. Some how I made a parsing error, and I need help finding it! Thank you!
classdef drunk_walking
properties
stepSize = 1
position = [0 0]
end
methods
function step(self)
dire = randi(4);
%Positive X
if dire == 1
self.position(1) = self.position(1) + 1;
%Negative X
elseif dire == 2
self.position(1) = self.position(1) - 1;
%Positive Y
elseif dire == 3
self.position(2) = self.position(2) + 1;
%Negative Y
elseif dire == 4
self.position(2) = self.position(2) - 1;
end
end
end
end
expr = drunk_walking; %This line is the parsing error
expr.step()
disp(expr.position)
2 Comments
Steven Lord
on 4 Oct 2020
Edited: Steven Lord
on 4 Oct 2020
Can you show the full and exact text of the error message you receive? Please include all the text that you see in red (error) and/or orange (warning) when you run your code.
Can you also tell us if the line "expr = drunk_walking;" is located inside the file drunk_walking.m, if you execute it in the Command Window, or if you have it in another file that produces the error when you run it?
Answers (1)
Steven Lord
on 5 Oct 2020
"expr = drunk_walking;" is located inside the .m file.
Move that line and the ones following it out of the classdef file. You can run those in a separate program file or you can type them in the Command Window. While you can define class-related functions in the classdef file after the end matching the classdef keyword, you can't just put arbitrary code there.
You are also going to need to modify the definition of your step method.
function step(self)
By default, classes in MATLAB have value semantics not handle semantics. See this documentation page for a description of what that means and this documentation page for a description of how this differs from object behavior in other languages. Because your class is a value class, modifying self in the step method is only modifying the copy inside that method. It doesn't modify the object that was passed into the method. You can either return the modified object from the method (and call the method with an output argument to receive that modified object) or make your class a handle class.
0 Comments
See Also
Categories
Find more on Function Creation 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!