如何在 Matlab 编程中设置限制

How to put limit in Matlab programming

所以我想生成一个像 theta= asind(x) 这样的方程,然后我编写了一个这样的程序:

x=0.5:5
theta=asind(x)
if x>1
theta = out of range
otherwise x=<1
end
fprintf('theta')

但是报错: xrdError:文件:xrd.m 行:4 列:17 意外的 MATLAB 表达式。

请帮帮我

你说你想让theta的元素在x的对应值超出范围时说"out of range",否则显示[=的反正弦15=].

这在 Matlab 中有点奇怪,因为 Matlab 中的数据要么是数字数组,要么是字符数组,而不是数字和字符的混合。

一种通过使用所谓的元胞数组来混合数字和字符的方法。元胞数组可以这样创建

cell1 = {};
cell2 = cell(5, 1);

然后你像这样分配和访问元素

cell1{1} = 'Hello';
cell1{2} = 7;
disp(cell{1})

所以(我认为)你想写的程序看起来像

x = (0.5 : 5)';
theta = cell(size(x));

for i = 1:length(x)
    if x(i) < -1 || x(i) > 1
        theta{i} = 'Out of range';
    else
        theta{i} = asind(x(i));
    end
end

x, theta

输出

x =

0.5000
1.5000
2.5000
3.5000
4.5000


theta = 

[30.0000]
'Out of range'
'Out of range'
'Out of range'
'Out of range'

但是,您可能应该重新考虑您希望程序做什么,因为元胞数组在 Matlab 中不是特别容易处理的数据类型。

明智的做法是将无效或缺失的值设置为 NaN(不是数字)。这无需循环即可轻松完成:

x=0.5:0.1:5;  % changed spacing so there is more than one valid x
theta=asind(x);
theta(x>1)=NaN;
plot(x,theta); % will plot only the valid values