Search code examples
matlabsymbolic-math

How to loop through indexed symbolics Matlab


so what im trying to do is to refer to different symbolics by indexing as you would with a vector

syms k_1 k_2 k_3 
for i= 1:3
    'expression to get k_i'
end

Desired answer would be k1 k2 k3.

I do not intend to do this with a vector created by the sym function unless there's a way to assign a matrix to a vector position without getting this error

error message.


Solution

  • You can add them all to a struct, then use dynamic referencing to the ith field name:

    % Create symbolic vars
    syms k_1 k_2 k_3
    % Assign to struct
    K.k_1 = k_1;
    K.k_2 = k_2;
    K.k_3 = k_3;
    % Loop through 
    for ii = 1:3
        kstr = sprintf('k_%d', ii); % = 'k_1', 'k_2', ...
        ki = K.(kstr);              % equivalent to ki = K.k_1 etc
    end
    

    Equivalently, once you have the struct you can just use the field names, although it's a bit less explicit which field you're accessing each iteration.

    f = fieldnames(K);
    for ii = 1:numel(f)
        ki = K.(f{ii});
    end