Skip to content

MATLAB Idiosyncracies

Michelle Sands edited this page Nov 6, 2025 · 3 revisions

Tips for Young Matlab-ers

Foreach Loops

Matlab allows foreach loops with the syntax

for instance = array
    % some logic related to instance x of array
end

But ONLY for 1xn arrays, not for nx1 arrays! You will need to transpose the array using the ' operator at the end of the array if you want to foreach through an nx1 array.

Categoricals

I used categoricals because they're the easiest way I could find to dynamically code dropdowns for component config. They're a bit of a nightmare to work with, and the documentation / forum activity for them is less robust than I'd like, so here are some bits I figured out:

if you want to extract the value from a categorical, I extracted it from its categories() like this:

newVal = src.Data.values{rownum};
    if iscategorical(newVal)
        cat = categories(newVal);
        idx = find(categorical(cat) == newVal);
        newVal = cat{idx};
    end

If you want to set the displayed value of a ComponentProperty as a categorical, I did it like this:

cat = prop.getCategorical; %nb look in ComponentProperty for this. It is not a built-in function.
configVal = component.ConfigStruct.(rowNames{fnum});
if ischar(configVal)
    configCat = categorical(cellstr(configVal));
    idx = find(cat == configCat);
    values{fnum} = cat(idx);
elseif isstring(configVal)
    configCat = categorical(cellstr(configVal));
    idx = find(cat == configCat);
    values(fnum) = {cat(idx)};
elseif isnumeric(configVal)
    configCat = categorical(configVal);
    idx = find(cat == configCat);
    values(fnum) = {cat(idx)};
end

Look at all those different ways to use brackets!

Also remember with categoricals that they only accept certain kinds of input: a numeric array, logical array, string array, or cell array of character vectors.

Calling anonymous functions with additional arguments

function createPanelThermode(obj,hPanel,~,idxThermode,nThermodes)
obj.h.(thermodeID).panel.params = uipanel(obj.h.fig,...
    'CreateFcn',    {@obj.createPanelThermode,ii,length(obj.s)});

Possibly helpful features

  • Data Linking - dynamic updates of plots as the data changes. Doesn't work on some kinds of plots and requires named variables though.

Clone this wiki locally