I'm trying to use Arduino in Matlab. cause I used Arduino in some function I had to define Arduino as a global variable.

clc,clear,close all;
global a
a = arduino();
some functions
clear a

at the end of my code I clear the variable but as I run the code again this error appear:

Failed to open serial port (user COM) to communicate with board Uno. ...
 Make sure there is no other MATLAB arduino object for this board.

I guess the global function can't be clear by clear command so I tried clear all instead clear in the last line. It works perfect as I run it again and again but as you know this is Matlab tips for clear all command

Using clear all causes MATLAB® to recompile previously cached code, 
and can decrease performance.

I've tried delete(a) so the result was:

Error using arduino/delete
Cannot access method 'delete' in class 'arduino'.

any help would be appreciated.

  • What does contain the global variable a = arduino(); ?
    – J. Piquard
    Dec 30, 2016 at 20:28
  • cause it's recall in all sub functions. like writePWMDutyCycle(a,E1, 0); Dec 30, 2016 at 23:25
  • sub functions use local value by default and save in separated location in matlab. one way is use a as an input argument for all of function. but i'm looking for another solution. Dec 30, 2016 at 23:30

1 Answer 1


In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html

In your case should be: clearvars -global a;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.