MATLAB. Love it. At the moment, though? Frustrated. Here’s some generalized code that I’m working on:
classdef particle properties x_pos % x position y_pos % y position x_upd % x update value y_upd % y update value end methods function b = particle() x_pos = 0; y_pos = 0; x_upd = rand(); y_upd = rand(); end function objs = update(objs) % Update x and y objs.x_pos = objs.x_pos + objs.x_upd; objs.y_pos = objs.y_pos + objs.y_upd; end end end
So the problem lies in my update function. Well, there isn’t really a problem with the code posted, one could use the following main script and it’ll run just fine.
one_particle = particle(); one_particle = update(one_particle);
The update method will run just fine and dandy. My problem? Trying to get this to run in a structure array. That is, getting the following main script to work.
ten_particles(10) = particle(); ten_particles = update(ten_particles);
The first line creates a structure array of size 1 by 10. When the update function is called in line 2, it tries to perform addition on the structure array, which it can’t do. The output of a structure array is a comma separated list, and MATLAB cannot do normal operations (like addition) on comma separated lists.
So the solution?
function objs = update(objs, walls) % Update x and y for ii = 1:numel(objs) objs(ii).x_pos = objs(ii).x_pos + objs(ii).x_upd; objs(ii).y_pos = objs(ii).y_pos + objs(ii).y_upd; end end
Which bothers me to no end. Why? Because my whole reason for creating a structure array was to take advantage of the speed of vector operations within MATLAB. That is, operations complete faster when done as vectors rather than as elements within a loop. Oh well, maybe a future build of MATLAB will allow structure arrays to be written and read as vectors.