I'm attempting to make a crude implementation of the AP CS 'gridworld' using matlab, albiet with fewer classes. So far I have a superclass 'Location' with the properties row and col. Next I have 'Grid' with just a cell array called grid. Using the Grid.get command, I can retrieve objects from that cell array. The problem though, is that I cannot get the Grid.put function to work. Testing without using the function allows me to put test strings into testGrid.grid{}, but the function doesn't seem to work.
classdef Location
properties
row;
col;
end
methods
%constructor, intializes with rows/columns
function loc = Location(r,c)
if nargin > 0
loc.row = r;
loc.col = c;
end
end
function r = getRow(loc)
r = loc.row;
end
function c = getCol(loc)
c = loc.col;
end
function display(loc)
disp('row: ')
disp(loc.row)
disp('col: ')
disp(loc.col)
end
end
Grid class, child of location:
classdef Grid < Location
properties
grid;
end
methods
function gr = Grid(rows, cols)
if nargin > 0
gr.grid = cell(rows,cols);
end
end
function nrows = getNumRows(gr)
[nrows,ncols] = size(gr.grid);
end
function ncols = getNumCols(gr)
[nrows,ncols] = size(gr.grid);
end
function put(gr,act,loc)
gr.grid{loc.getRow,loc.getCol} = act;
end
function act = get(gr,loc)
act = gr.grid{loc.getRow(),loc.getCol()};
end
end
Finally, the test commands from the command window
testLoc = Location(1,2)
row:
1
col:
2
testGrid = Grid(3,4)
row:
col:
testGrid.put('testStr',testLoc)
testGrid.get(testLoc)
ans =
[]
testGrid.grid{1,2} = 'newTest'
row:
col:
testGrid.get(testLoc)
ans =
newTest
Thanks for any insight!
You need to return the object from your functions and use that as your new object. So
function put(gr,act,loc)
gr.grid{loc.getRow,loc.getCol} = act;
end
Should be
function gr = put(gr,act,loc)
gr.grid{loc.getRow,loc.getCol} = act;
end
And then you can use it like
testGrid = Grid(3,4)
testGrid = testGrid.put(act, loc)
testGrid.get(loc)
And you can also chain the calls
testGrid.put(act, loc).get(loc)
Related
When I run the code below I got this error Brace indexing is not supported for variables of this type.
function [R, Q] = rq_givens(A)
Q = { eye(size(A,2)) };
R = { A };
I =eye(size(A,1));
Qs={ };
k=1;
for i=1:size(A,2)
for j= size(A,1):-1:i+1
y= -A(j,i);
x= A(i,i);
alpha = atan(y/x);
c = cos(alpha);
s= sin(alpha);
temp = I;
temp(i,i)=c;
temp(i,j)=-s;
temp(j,i)=s;
temp(j,j)=c;
A = temp * A;
Qs{k} = temp;
k=k+1;
end
end
Q=I;
for i=k-1:-1:1
Q = Q*Qs{i};
end
Q= Q';
R= A;
end
It's an assignment that I am doing so all I can do is to change the function above,
The code to call the function is below and must stay the same.
A = randn(6,4);
[R,Q] = rq_givens(A)
for i = 1:length(R)
disp("Q orthonormal?")
Q{i}*Q{i}'
Q{i}'*Q{i}
disp("R upper triangular?")
R{i}
end
R{end}*Q{end} - A % Equal ?
Data types of R, Q are changed to numeric type from cell type inside function call.
At the second line, R is cell array, but the last line of function "rq_given" changes the type of R to numeric matrix.
Thus, R{i} is invalid. Similar issue can be seen with Q also.
I have a class in MATLAB that represents an imaginary number. I have a constructor and two data members: real and imag. I am playing with overloading operator in a class and I want to make it work with matrices:
function obj = plus(o1, o2)
if (any(size(o1) ~= size(o2)))
error('dimensions must match');
end
[n,m] = size(o1);
obj(n,m) = mycomplex();
for i=1:n
for j=1:m
obj(i,j).real = o1(i,j).real + o2(i,j).real;
obj(i,j).imag = o1(i,j).imag + o2(i,j).imag;
end
end
end
But I don't want to use for loops. I want to do something like:
[obj.real] = [o1.real] + [o2.real]
But I don't understand why it does not work... the error says:
"Error in + Too many output arguments".
I know that in MATLAB it is good to avoid for loops for speed up... Can someone explain me why this does not work, and the right way to think about vectorization in MATLAB with an example for my function?
Thanks in advance.
EDIT: definition of my complex class:
classdef mycomplex < handle & matlab.mixin.CustomDisplay
properties (Access = public)
real;
imag;
end
methods (Access = public)
function this = mycomplex(varargin)
switch (nargin)
case 0
this.real = 0;
this.imag = 0;
case 1
this.real = varargin{1};
this.imag = 0;
case 2
this.real = varargin{1};
this.imag = varargin{2};
otherwise
error('Can''t have more than two arguments');
end
obj = this;
end
end
end
Consider the implementation below. First some notes:
the constructor can be called with no parameters. This is important to allow preallocating object arrays: obj(m,n) = MyComplex()
for convenience, the constructor accepts either scalar of array arguments. So we can call: c_scalar = MyComplex(1,1) or c_array = MyComplex(rand(3,1), rand(3,1))
the plus operator uses a for-loop for now (we will later change this).
(Note that I skipped some validations in the code, like checking that o1 and o2 are of the same size, similarly for a and b in the constructor).
classdef MyComplex < handle
properties
real
imag
end
methods
function obj = MyComplex(a,b)
% default values
if nargin < 2, b = 0; end
if nargin < 1, a = 0; end
% accepts scalar/array inputs
if isscalar(a) && isscalar(b)
obj.real = a;
obj.imag = b;
else
[m,n] = size(a);
obj(m,n) = MyComplex();
for i=1:m*n
obj(i).real = a(i);
obj(i).imag = b(i);
end
end
end
function obj = plus(o1, o2)
[m,n] = size(o1);
obj(m,n) = MyComplex(); % preallocate object array
for i=1:m*n % linear indexing
obj(i).real = o1(i).real + o2(i).real;
obj(i).imag = o1(i).imag + o2(i).imag;
end
end
end
end
An example of using the class:
% scalar objects
>> c1 = MyComplex(1,2);
>> c2 = MyComplex(3,4);
>> c3 = c1 + c2
c3 =
MyComplex with properties:
real: 4
imag: 6
% array of objects
>> c4 = [c1;c1] + [c2;c2]
c4 =
2x1 MyComplex array with properties:
real
imag
Now here is a vectorized version of the plus method:
function obj = plus(o1, o2)
[m,n] = size(o1);
obj(m,n) = MyComplex();
x = num2cell([o1.real] + [o2.real]);
[obj.real] = deal(x{:});
x = num2cell([o1.imag] + [o2.imag]);
[obj.imag] = deal(x{:});
end
I'm using the syntax: [objarray.propName] to reference a property in object arrays, this return the values as a vector.
For the opposite of assigning a property in an object array, I use comma-separated lists, thus I had to convert to a cell array to get the x{:} convenient syntax.
Note that the deal call is not strictly needed, we could write the assignment without it:
[obj.real] = x{:};
The line obj(n,m) = mycomplex() looks very suspicious. I think what you want to do there is obj = mycomplex(n,m) instead.
I can't see the rest of your code, but it's miraculous to me that this line even works. I suspect that you have an obj variable stored somewhere already, and this code simply overwrites one entry of that variable. I predict that if you clear all variables, it's going to fail on that line.
Again, it's very difficult to understand what happens without knowing what mycomplex() actually does.
This is my original code:
function a = graph_times()
merge_times = [];
for i = 100:100:1000
curr = sort_timer(i);
merge_times = [merge_times, curr(1)];
end
plot(100:100:1000, merge_times);
a = 1;
end
I want to modify this code so that it plots trendlines for both insertion_sort and merge_sort on the same graph.
Below are the functions for merge_sort and insertion_sort
function c = insertion_sort(list1)
inserted = [];
for i = 1:size(list1,2)
inserted = insert_in_order(inserted,list1(1,i))
c = inserted
end
steps2=0;
function b = merge_sort(nums)
if size(nums,2) == 1
b = nums;
return;
end
You can give several sets of coordinates to MATLAB's plot function. You can plot the times of the two sorting algorithms like so:
plot(100:100:1000, merge_times, 100:100:1000, insertion_times);
I am attempting to build a distributed array of handle class objects in MATLAB and I would like to extract a specific handle from this vector for use on the command line. Given the code below, I would like the following to execute. I am running this on with two labs (matlabpool 2). The getValue function is what I need assistance with, thanks...
vec = buildArray;
h = getValue(vec,6);
h.id
ClassA.m:
A class that I would like to distribute in parallel.
classdef ClassA < handle
properties
id;
end
methods
function obj = ClassA(id)
obj.id = id;
end
end
end
buildArray.m:
A function to build codistributed array from local instances of ClassA.
function vec = buildArray
X(:,1) = 1:10; % create ids
gsize = size(X); % the global size
X = distributed(X); % distribute the ids
spmd
x = getLocalPart(X); % extract the local ids
local = cell(length(x),1); % create local storage for handles
% Create the class instances
for i = 1:length(x);
local{i} = ClassA(x(i));
end
% Build the codistributed array of handles
codist = codistributor1d(codistributor1d.unsetDimension, ...
codistributor1d.unsetPartition, gsize);
vec = codistributed.build(local,codist);
end
getValue.m:
This is the function that I need help with, currently it just displays what lab that contains the class with the specified id. I would like for it to return the handle so it may be used from the command line. How is this done?
function h = getValue(vec, id)
h = []; % just so it will not throw an error
spmd
local = getLocalPart(vec);
for i = 1:length(local);
if local{i}.id == id;
% Export h here
disp(['ID ', num2str(id), ' is on lab ', num2str(labindex)]);
break;
end
end
end
I was able to get my problem working using this for getValue.m, is there a better way?
function h = getValue(vec, id)
spmd
local = getLocalPart(vec);
idx = [];
for i = 1:length(local);
if local{i}.id == id;
idx = i;
break;
end
end
codist = codistributor1d(codistributor1d.unsetDimension, ...
codistributor1d.unsetPartition, [numlabs,1]);
IDX = codistributed.build(idx, codist);
end
c = gather(vec(IDX));
h = c{1};
In a class with the dependent property c, I would like to call c's setter with a third argument that equals 'a' or 'b', choosing which independent property to alter in order to set c.
The code is
classdef test < handle
properties
a
b
end
properties (Dependent = true)
c
end
methods
function c = get.c(obj)
c = obj.a + obj.b;
end
function obj = set.c(obj, value, varargin)
if(nargin == 2)
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'a') % how do I enter this loop?
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'b') % or this?
obj.b = value - obj.a;
end
end
end
end
This call works:
myobject.c = 5
But how do I call the setter with a third parameter equaling 'a' or 'b'?
You can't. set always accepts only two arguments. You could work around it with an additional dependent property:
classdef test < handle
properties
a
b
end
properties (Dependent = true)
c
d
end
methods
function c = get.c(obj)
c = obj.a + obj.b;
end
function d = get.d(obj)
d = c;
end
function obj = set.c(obj, value)
obj.a = value - obj.b;
end
function obj = set.d(obj, value)
obj.b = value - obj.a;
end
end
end
or by choosing a different syntax and/or approach:
myObject.set_c(5,'a') %// easiest; just use a function
myObject.c = {5, 'b'} %// easy; error-checking will be the majority of the code
myObject.c('a') = 5 %// hard; override subsref/subsasgn; good luck with that
or something else creative :)