Search code examples
arraysmatlabfor-loopmatrixparfor

avoid eval for the sake of eval Matlab


I'm currently evaluating my arrays as eval(['P' num2str(jj) '(i,:)']) where P1 P2 are my arrays, and I'm only interested all both my arrays from (i,1:3) and where i is used to rows and jj for evaluating 1 2 arrays. I want to avoid eval() as I want to use PCT for parallel processing of both arrays, as parfor loop doesn't support eval() and also Matlab also suggests that avoid it wherever U can, Now what are the possible solutions/suggestions according to my scenario.

My Code:

n=2;
for i=1:10
for jj=1:n
eval(['P' num2str(jj) '(i,:)']);
end
end

Solution

  • Try using a cell array:

    P = cell(1,2);
    P{1} = P1;
    P{2} = P2;
    

    Now you can do it like this:

    n=2;
    for i=1:10
        for jj=1:n
            P{jj}(i,:)
        end
    end