matlab不能使用/除法

发布于 2025-01-07 13:48:07 字数 696 浏览 0 评论 0原文

我有一些简单的函数,它接受一个值

,该值是检查多个 if 或 elseif 语句以计算另一个值的值。

问题是在尝试运行时似乎发现一个错误,其中显示

Error using / 矩阵尺寸必须一致。

abc 错误(第 9 行) a=5000/克;

代码如下

function abc(g)


if (g == 100)
   a = 1;
elseif (g <= 99 & g >= 50)    
   a = 200 -2*g;
elseif (g <= 50 & g >= 1)
   a = 5000 / g;
else
  warning('Invalid value passed, a defaults to 1');
  a =1;
end
end

所以,我传入 abc 100,我希望 a 为 1,但它会遍历每个 if / elseif 并在 a = 5000/g 上抛出错误

我还应该提到我最初尝试使用 && ;在 elseifs 中,但这也给出了一个错误,表示

操作数为 ||和&&运算符必须可转换为逻辑标量值。

abc 错误(第 6 行) elseif (g <= 99 && g >= 50)

有人知道这里发生了什么吗? 谢谢

I have some simple function that takes in a value

This value is the checked off a number of if or elseif statements to calculate another value.

The problem is it seems to find an error when trying to run which says

Error using /
Matrix dimensions must agree.

Error in abc (line 9)
a = 5000 / g;

the code is as follows

function abc(g)


if (g == 100)
   a = 1;
elseif (g <= 99 & g >= 50)    
   a = 200 -2*g;
elseif (g <= 50 & g >= 1)
   a = 5000 / g;
else
  warning('Invalid value passed, a defaults to 1');
  a =1;
end
end

So, im passing in abc 100 and i expect a to be 1 but instead it runs through each if / elseif and throws an error on a = 5000/g

I should also mention that i initially tried using && in the elseifs but this also gave an error which said

Operands to the || and && operators must be convertible to logical scalar values.

Error in abc (line 6)
elseif (g <= 99 && g >= 50)

Anybody any idea whats going on here ?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素年丶 2025-01-14 13:48:07

您可能将一个矩阵传递给您的函数,例如,当您调用

abc(yourdata)

yourdata时,实际上不是一个数字,而是一个矩阵。如果您直接致电,

abc(100)

您不应该看到您的问题(或者您会吗?)。

换句话说,你的主要问题不在你的函数内部,而是当你调用它时!

根据您的描述,您似乎将 yourdata(1) 设置为要测试的值 100,但矩阵的其他一些元素具有不同的值,这就是 if 构造分支到 else 情况。在那里,如果您想做逐元素除法 而不是 矩阵除法

但实际上,您可能只需要确保在调用函数时 yourdata 是标量。

You are probably passing a matrix to your function, e.g. when you call

abc(yourdata)

yourdata is actually not one number, but a matrix. If you called directly

abc(100)

you should not see your problem (or do you?).

In other words, your main problem is not inside your function, but when you call it!

Given your description, it seems that you set yourdata(1) to the value 100 that you want to test, but some other element of the matrix has a different value, which is why the if construct branches into the else case. There, you need ./ instead of / if you want to do element-wise division instead of matrix division.

But really you probably just need to make sure that yourdata is scalar when you call your function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文