Search code examples
matlabfunctionvariablesworkspace

Use variables with changing names from workspace in MatLab function


I am using a function named cpselect (Image Processing Toolbox) which basically returns the pixel value (x,y) of the points I want in an image. The pixel value is then saved in workspace as a variable. So I have two problems:

  1. I need to use these variables in a function. I have several images, and after I use cpselect I get fixedPoints, fixedPoints1, fixedPoints2, etc... in the workspace.
function [] = ControlPoints()
%function that reads images in directory and uses cpselect to each 
    imagefiles = dir('*.jpg');      
    nfiles = length(imagefiles); 
    for ii=1:nfiles
       currentfilename = imagefiles(ii).name;
       currentimage = imread(currentfilename);
       cpselect(currentimage,currentimage); 
       pause; 
     end
     a = fixedPoints1;  % returns error(undefined variable)   
end

Is there a way of using these variables in the same function? They are created in the workspace, and not in the function itself, which is why I get errors when I try to use it.

  1. After I find a way to use it, there's the second problem. The variables I get are fixedPoints, fixedPoints1, fixedPoints2, etc... I want to put all of them in a cell array to use in the same function or in another one. How exactly can I do this? I get that its bad to dynamically create variable names like that but given the circumstances I don't think I have a choice.

thanks in advance


Solution

  • Both issues can be taken care of using the last syntax shown in the documentation:

    [selectedMovingPoints,selectedFixedPoints] = cpselect(currentimage,currentimage,'Wait',true)
    

    The returned arrays are px2 numeric arrays, where each row is one of the points selected.