Help with understanding a piece of code

14 views (last 30 days)
Vicente
Vicente on 2 Jun 2015
Edited: per isakson on 19 Jan 2021
Hi all!
Could you please help me understand this piece of code here?
classdef Tire<handle
properties (Constant)
DEFAULT_DIR = 'C:\Users\Vicente Silva\Desktop\';
end
properties
Name;
Dir;
end
properties
% here comes the declaration of a bunch of properties,
% which are not important for understanding the code itself
end
methods
function tire = Tire(varargin)
tire.Name = varargin{1};
if nargin > 1
tire.Dir = varargin{2};
else
tire.Dir = Tire.DEFAULT_DIR;
end
try
load([tire.Dir tire.Name '.mat']);
catch
tire = tire.LoadFromTir([tire.Name '.tir']);
tire.Fzo = tire.FNOMIN;
end
end
function tire = LoadFromTir(tire, tir_filename)
tirfile = fopen([tire.Dir tir_filename], 'r');
line = fgetl(tirfile);
while ischar(line)
if regexp(line, '^[A-Z]')
prop = strsplit(line,{'=' '$'});
propname = char(strtrim(prop{1}));
if isprop(tire, propname)
propval = char(strtrim(prop{2}));
if ~strncmpi(propval,'''',1)
tire.(propname) = str2double(propval);
else
tire.(propname) = strrep(propval, '''', '');
end
end
end
line = fgetl(tirfile);
end
fclose(tirfile);
end
function Save(tire)
save([tire.Dir tire.Name '.mat'], inputname(1));
end
I have used 'help' command for most of the commands I didn't know, but it didn't help understand much. More importantly, it surely didn't allow me to understand how to keep on writing pieces of code myself! Keep in mind, this is part of a work I'm currently developing with a friend of mine. But he is the computer sciences student, and I'm the mechanical engineering one. I only understand a bit of coding in MATLAB and Simulink. This here is practically russian for me. I have tried asking my friend for more help and clarifications, but it seems he is busy. I really wish I could do all this work on my own, but I'm at a much more superficial level of coding right now. My work is due at the 15th this month, and without any help I won't be able to finish everything. Please, help me!

Accepted Answer

Adam
Adam on 2 Jun 2015
Edited: Adam on 2 Jun 2015
Which part of it do you not understand? There are a number of different elements in that code and if you already understand some aspects it would be a waste of time someone explaining them in detail! So in relatively little detail:
  1. Properties blocks store class properties that are available to any function in the class, similar to variable in function scope, but referred to with the object scope when used (I assume you have no problem with these)
  2. Methods blocks contain the functions that you can call. In this case all may be called from external to the class, whether that is the intention or not.
  3. The first function is the constructor which takes a variable sized array of inputs and creates the actual object instance. It does no validation of the inputs, but the expected inputs can be worked out easily enough from the code which assigns them to the relevant properties. The body of the constructor appears to try to load data from a .mat file and if it fails it loads from a .tir file instead (which I assume is always valid since it has no error handling on that part).
  4. The second function is the loadFromTir called in the constructor when loading from .mat fails. The body of that uses regular expressions to extract the required information to store in the class properties using dynamic strings for the property names.
  5. The save function should theoertically save the tire name and directory to a mat file, but since inputname appears to be undefined I assume that function will crash.
The following syntax:
tire.(propname)
allows you to use dynamic strings to assign to properties, but it does come with the assumption that ' propname ' is something that evaluates to one of the properties defined in your properties blocks. It is a method I have used to good effect on a few occasions, but can easily become the source of difficult to track down bugs due to its obfuscation of the property names it is actually assigning to. Basically this will load in and assign all those properties you omitted as "not important for understanding the code itself".
The actual code in the load function is mostly just dynamic string manipulation with regular expressions and other string manipulation functions that trim off extra bits of the string to get the correct property names in the strings to then assign as mentioned above.
If you need more understanding of the exact nature of the regexp and string manipulations I will let someone else add that as it is something I battle with occasionally and forget quickly afterwards!! Your tags suggest it is the OOP aspect you are struggling with though.
  3 Comments
Adam
Adam on 3 Jun 2015
is the Matlab OOP oracle. It is very long, but is obviously a reference, not something to read from start to finish.
I have been working with Matlab for ~9 years now (though mixed in with some long periods of C++ when I didn't use Matlab), but when I first picked up OOP and decided to start using it 3 years ago it took me only 2 weeks, with that document for help, to get my first UI + class piece of functionality working so it can be picked up quite quickly (as oppose to just a UI with everything in the callbacks and other functions as I did previously).
Always remember you can put breakpoints in code to see what is going on and you can use the command line within a breakpoint to try out code and see what it does. I do this as regularly now as I did when I first started Matlab as it is invaluable for understanding what code does.
By trade I am a research engineer which covers more of a breadth of skills than the depth of a pure software engineer, but I like it that way. I have the skills to go from coming up with ideas all the way through to a finished product in Matlab which sounds like what you are aiming to do too. It is certainly worth the effort to develop the programming skills alongside the expertise in your other areas.

Sign in to comment.

More Answers (3)

Guillaume
Guillaume on 2 Jun 2015
Edited: Guillaume on 2 Jun 2015
Don't computer science students learn to comment their code? The lack of comment should be reason enough to fail the assignment. At the very least inputs and outputs of functions should be documented with a short comment about the purpose of the function.
You don't say what part of the code is a problem. We obviously can't explain every single line of code, that'd be the equivalent of teaching you matlab.
The code defines three methods of the class, a constructor that construct the object by reading it from a .mat file or if that fails, by calling the LoadFromTir. The loadFromTir function reads the object properties by parsing them from a .tir text file. Finally there is a function to save the object to a .mat file.
Other than the regular expression there's nothing particularly advanced in the code. Even the regular expression is simple. It just tells you whether there's any character that is not an uppercase letter in the string.

agnes jerusha
agnes jerusha on 22 Oct 2019
lp1=(model.prior(1));
for j=1:size(data,2)
if model.likelihood(1).feature{j}(data(j))~=-Inf
lp1=lp1+(model.likelihood(1).feature{j}(data(j)));
else
class=2;
return;
end
end
%calc lp0
lp0=(model.prior(2));
for j=1:size(data,2)
if model.likelihood(2).feature{j}(data(j))~=-Inf
lp0=lp0+(model.likelihood(2).feature{j}(data(j)));
else
class=1;
return;
end
end
  1 Comment
Steven Lord
Steven Lord on 22 Oct 2019
This isn't related to the main question. Please ask it as a separate question (with an actual question, not simply a block of code.)

Sign in to comment.


WAN NOR NAZIRA MUSTAPA KAMAL
Edited: per isakson on 19 Jan 2021
Hi all can anyone help me to understand this code?
%% setup
hold all
a = arduino('COM3', 'Uno');
mpu = i2cdev(a,'0x68'); %mpu adress is normally 0x68
writeRegister(mpu, hex2dec('B6'), hex2dec('00'), 'int16'); %reset
data = zeros(10000,14,'int8'); %prelocating for the speed
j = 1;
a1 = animatedline('Color',[1 0 0]);
a2 = animatedline('Color',[0 1 0]);
a3 = animatedline('Color',[0 0 1]);
legend('Accel_x','Accel_y','Accel_z')
%% loop
while(true)
x=1;
for i=59:72 % 14 Data Registers for Accel,Temp,Gyro
data(j,x) = readRegister(mpu, i, 'int8');
x = x + 1;
end
y = swapbytes(typecast(data(j,:), 'int16')) %if your system is big-endian remove the swapbytes function
addpoints(a1,j,double(y(1)));
addpoints(a2,j,double(y(2)));
addpoints(a3,j,double(y(3)));
j = j+1;
drawnow limitrate
end
  1 Comment
Steven Lord
Steven Lord on 19 Jan 2021
This isn't related to the main question. Please ask it as a separate question.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!