Skip to content

Instantly share code, notes, and snippets.

@wmayner
Created July 12, 2018 16:51
Show Gist options
  • Save wmayner/c003e4543fa1b48089af372b7437c656 to your computer and use it in GitHub Desktop.
Save wmayner/c003e4543fa1b48089af372b7437c656 to your computer and use it in GitHub Desktop.
MATLAB coding style

Code style

Functions are preferred to scripts.

Nested structs are used to hold data, so that the data is labeled explicitly rather than relying on an indexing convention.

Fields in structs can be dynamically accessed with the someStruct.(fieldName) syntax; i.e.,

fieldName = 'someField';
someStruct.(fieldName) == someStruct.someField;  % is true

and they can be iterated over in a loop like so:

fields = fieldnames(someStruct);
for i = 1:length(fields)
  % Note the cell-array indexing with braces rather than parentheses
  field = fields{i};
  doSomethingWith(someStruct.(field));
end

or, more concisely,

for field = fieldnames(someStruct)
  % This line is strange but necessary because MATLAB has awful semantics
  field = field{1};
  doSomethingWith(someStruct.(field))
end

The second construction is more readable, but doesn't work with parfor loops.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment