How to write indicator function in matlab

扶醉桌前 提交于 2019-12-11 06:17:42

问题


I am a new user of matlab and I want to tackle the following problem:

I want to construct a piecewise constant function f. f should be an anonymous function like f=@(t)1[0,0.25)(t). However, the number of intervals for the piecewise constant function is not fixed in general. Instead, the piecewise interval depends on users input.

For example, if one enters 4, the piecewise interval becomes

[0,0.25), [0.25,0.5), [0.5,0.75) and [0.75,1)

then

f=@(t)a1*1[0,0.25)(t)+a2*[0.25,0.5)(t)+a3*1[0.5,0.75)(t)+a4*1[0.75,1)(t);

While if one enters 5, the piecewise interval becomes

[0,0.2), [0.2,0.4), [0.4,0.6), [0.6,0.8) and [0.8,1)

Are there any good ways to tackle the problem?


回答1:


Assuming that the weights a1,...,ak are already defined, you can use the following approach:

%defines weight vector. for example: a1=1, a2=2, a3=3, a4=4,a5=5
A = 1:5;  
%defines a range vector
ranges = [0:(1/length(A)):1,inf];
%The padding is for handling cases where t<0 or t>=1
APadded = [0,A,0];
%define f
f=@(t)APadded(find(t<ranges,1,'first'))

Result:

f(0.1) = 1
f(0.3) = 2
f(0.5) = 3
f(0.7) = 4
f(0.9) = 5
f(-0.1) = f(1.1) = 0;


来源:https://stackoverflow.com/questions/37349914/how-to-write-indicator-function-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!