Your global variable 'serialObject' has no data in it. That's the root cause. We'll see why.
When the code hits the first disp statement, it displays 0 because there's no data in the global variable. By the time the code hits the second disp statement, you have deleted the local copy of the global variable 'serialObject'. So, the serialObject(index) = vargin(1); command creates a new local variable named 'serialObject'. And the disp statement displays the length of that local variable. This length depends on the input argument 'index' which in your case is 1.
clear only clears local copies of variables unless explicitly specified. You can read more about clearing global variables in the hyperlink.
In essence, your global variable 'serialObject' never gets assigned a value because of the clear command.
Also, it is generally not considered a good practice to use globals. Why it's not a good practice has been discussed several times on this forum. Here's one thread. You can search for more discussions.
Consider the following alternatives to have cleaner and safer code.
1. Pass serialObject as input and return it as an output once it is updated.
function [s, serialObject] = serialObj(serialObject, index, io, vargin)
% your code in here
end
2. Create serialObject variable inside the connect function and nest the serialObj function inside the connect function so that the serialObject variable is available to all calls of the serialObj function.
function s = connect(port, index, app)
serialObject = [];
% ... your code here
function s = serialObj(index, io, vargin)
% use serialObject without global now
% ... your code here
end
end