Home > OS >  How to loop through indexed symbolics Matlab
How to loop through indexed symbolics Matlab

Time:08-31

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.

CodePudding user response:

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

CodePudding user response:

Similarly to @Wolfie's answer, you can use a cell array:

syms k_1 k_2 k_3
k = {k_1, k_2, k_3};
for ii = 1:3
    ki = k{ii};
end

This is somewhat simpler than the struct solution, but doesn't preserve the variable names. In this case, k{1} is similar enough to k_1, so maybe this doesn't matter.

  • Related