Using Functions with System Objects

This documentation shows how to use System Objects with functions when running a MATLAB Function or Simulink model directly on a desktop computer.

Contents

Introduction

In these demos, will show how to use System Objects in functions. System Objects are used to perform image acquisition, computer vision, communication, and other operations in MATLAB. In general, system objects take a relatively long time to create but execute quickly. As a result, it is a waste of computing power to reinitialize them. The solutions are as follows:

Pass Into Function

This example shows how to pass system objects into a function.

This is useful when the same system object is needed in multiple functions. Initializing the system object once and passing it into functions is easier than constantly reinitializing the system object in functions.

%% Setup Video Acquisition and Video Player system objects
videoReaderObject = imaq.VideoDevice('winvideo',...
      'VideoFormat','MJPG_640x480',...
      'ReturnedDataType','uint8');
videoPlayerObject = vision.DeployableVideoPlayer();
%% Step the video reader to extract each frame and then visualize
idx = 0;
while(idx<=100) % run for 100 steps
    idx = idx + 1; % update iteration number
    stepFunction(videoReaderObject,videoPlayerObject);
end
%% Step Function: acquire video and visualize
function stepFunction(videoReaderObject,videoPlayerObject)
    frame = step(videoReaderObject);
    step(videoPlayerObject,frame);
end

Open Example

Locally defined using persistent variables

This example shows how to define system objects locally in a function using persistent variables.

This method is useful because the user does not have to pass variables into functions, leading to long argument lists.

%% Step the video reader to extract each frame and then visualize
idx = 0;
while(idx<=1e6) % run for 100 steps
    idx = idx + 1; % update iteration number
    stepFunction;
end
%% Step Function: acquire video and visualize
function stepFunction
    %% Setup: setup video acquisition and players
    persistent videoReaderObject videoPlayerObject
    if isempty(videoReaderObject) && isempty(videoPlayerObject)
        %% Setup video file and camera readers
        % import video from camera using the imaq.VideoDevice System Object
        videoReaderObject = imaq.VideoDevice('winvideo',...
              'VideoFormat','MJPG_640x480',...
              'ReturnedDataType','uint8');
        %% setup video player
        videoPlayerObject = vision.DeployableVideoPlayer();
    end
    %% Step: acquire video and visualize
    frame = step(videoReaderObject);
    step(videoPlayerObject,frame);
end

Open Example