Generate long piecewise function

5 views (last 30 days)
Walter Biribicchi
Walter Biribicchi on 1 May 2020
Answered: Image Analyst on 4 May 2020
Hello,
I'm trying to implement a piecewise function in a for loop.
Basically I have a linear slope defined by two heights at the ends, and I want to discretize that slope into a piecewise function with an high number of member (10, 30, 100 or input-defined).
The best way I could think of was generating a string through a series of for loop (and a lot of num2str like functions) and copy-pasting it in the argument of a piecewise function, eg:
piecewise(0<=x<=0.16933,0.54111,0.16933<=x<=0.33867,......)
I'm sure there is a better way or a built-in fuction but cannot find anything

Answers (2)

Guru Mohanty
Guru Mohanty on 4 May 2020
Hi, you want to get piecewise value of the slope between two heights. You can use interp1and gradientfunction for this. Here is a sample code for it.
clc;clear all;
t1=0;t2=10; % Define position of two heights
height1=3; % Define Values of Two Heights
height2=5;
n=500; % Set Number of Members
tnew=linspace(t1,t2,n);
y1=interp1([t1 t2],[height1 height2],tnew);
slope=gradient(y1,tnew);

Image Analyst
Image Analyst on 4 May 2020
See my piecewise linear fit demo.

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!