带有 IF 语句的向量函数的 MATLAB 返回 [英] MATLAB return of vector function with IF statement

查看:19
本文介绍了带有 IF 语句的向量函数的 MATLAB 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用这样的向量的自写函数func":

I am calling a self written function 'func' of a vector like this:

x_values=[0 1 2];
result=func(x_values);

问题是在这个函数中我有一个 if 语句来确定输出.如果我将此函数应用于一个标量,我没有问题,但如果我将它应用于一个数字向量,if 语句不会完成他的工作.为什么?我该如何修复它?

The problem is that in this function i have an if statement to determine the ouput. If I apply this function to a scalar, I have no problem, but if I apply it to a vector of numbers, the if statement doesn't do his job. why? And how can i repair it?

function [y]=func(x)
if(x==0)
  y=0
else
  y=1./sin(x);
end
end

推荐答案

您需要分别对待零和非零条目.这可以通过索引轻松实现:

You need to treat the zero and non-zero entries separately. This is easily achieved via indexing:

function [y]=func(x)
xIsZero = x==0;

%# preassign y
y = x;

%# fill in values for y
y(xIsZero) = 0

y(~xIsZero) = 1./sin(x(~xIsZero))

这篇关于带有 IF 语句的向量函数的 MATLAB 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆