MATLAB: Loading variables & using ‘for’ loop for comman polyeig()

anti-patternevalevilfor loopMATLABvariables

Let us say, i've a series of matrices as K1, K2,….K(n)
I want to obtain eigen values and eigen vectors for the above mentioned matrices; like:
[X1 E1] = polyeig(K1,M)
[X2 E2] = polyeig(K2,M)
[X3 E3] = polyeig(K3,M) & so on
Can anyone suggest a for loop for it, where M is not a variable matrix. But X1,X2,X3…… & E1,E2,E3….. are variables.

Best Answer

It is not a good idea to name variable like K1, K2, K3, ... It makes code complicated: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. First I will convert K1, K2, ..., Kn to cell array and then return the output in cell arrays.
K = {K1, K2, K3, .., K10}; % list all the Kxx variables here
M; % matrix
[X, E] = cellfun(@(k) polyeig(k, M), K, 'uni', 0);
Access the results like this
X{1}; % first element of X
X{2}; % second element of X
..
X{end}; % last element of X
E{1}; % first element of E
E{2}; % second element of E
..
E{end}; % last element of E