MATLAB: If else for class of data

charclassifelseMATLABmatlab function

Hi all,
I have been trying to create a function which plots two inputs against each other and their derivatives against eachother on the same plot. I indend to use this function with data from a timetable. I want to be able to use a datetime input or a double in my xdata, so when xdata is a double it simply plots dx against dy, or when xdata is a datetime variable xdata is plotted against dy. Below is my function;
function createFig2(xdata,ydata) %xdata is either double or datetime, ydata is double
plot(xdata,ydata,'-k') %plot inputs
hold on
if class(xdata) == char('double') %check if xdata is double
dx = diff(xdata);
dy = diff(ydata);
plot(dx,dy,'--r')
else %if xdata is datetime
dy = diff(ydata);
plot(xdata,dy,'--r') %plot xdata against dy
end
hold off
xlabel('xdata')
ylabel('ydata')
end
When I attempt to run this function I get an error in Line 4;
"Matrix dimensions must agree.
Error in createFig2 (line 4)
if class(xdata) == char('double')".
I am not very familiar with ifelse statements or logically statements in matlab so I'm not sure how to fix this. Thank you in advance for your help! 🙂

Best Answer

if isa(xdata, 'double')
Or
if strcmp(class(xdata), 'double')
or
if class(xdata) == "double" %notice this is not 'double' but "double"