简体   繁体   中英

How to define a peicewise function in a function file - Matlab

I made a funnction file and defined a peicewise function inside it using conditionals and a for loop. I tried calling the function in a seperate m.file but the variables 't' and 'v' aren't showing in the workspace, rather it is just outputting a vector with the t values called 'ans.

I tried putting the exact code (without the function definition) into a regular m file and it worked just fine showing both variables t and v

    #function file
function [t, v] = VPieceWise(t_start, t_end);
t = t_start:0.01:t_end;
for i = 1:length(t);
    if (t(i) >= 0) && (t(i) <= 10);
        v(i) = 11.*(t(i).^2) - (5.*t(i));
    elseif (t(i) >= 10) && (t(i) <= 20);
        v(i) = 1100 - 5.*t(i);
    elseif (t(i) >= 20) && (t(i) <= 30);
        v(i) = 50.*t(i) + 2*((t(i)-20).^2.5);
    elseif (t(i) >= 30) && (t(i) <= 100);
        v(i) = 1520.*exp(-0.1.*(t(i)-30));
    elseif (t(i) >= -100) && (t(i) <= 0);
        v(i) = 0;
    end
end
end
#m file
clear all; clc; close all
t_start = input('enter the start time');
t_end = input('enter the end time');
VPieceWise(t_start,t_end)
plot(t,v)

Since your function has two outputs, you should also assign them when calling the function. If you do not do that, only the first output will be put in the ans variable.

So call your function as follows:

clear all; clc; close all
t_start = input('enter the start time');
t_end = input('enter the end time');
[t,v] = VPieceWise(t_start,t_end);
plot(t,v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM