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

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

问题描述

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

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

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


解决方案

您需要分别处理零和非零条目。这很容易通过索引实现:

 函数[y] = func(x)
xIsZero = x == 0 ;

%#preassign y
y = x;

%#填入y $ b $的值(xIsZero)= 0

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


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

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

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天全站免登陆