【问题标题】:How to create a simple graph Using Matlab如何使用 Matlab 创建一个简单的图形
【发布时间】:2017-06-18 08:56:23
【问题描述】:
sym t;
a = 10;
b=10;
V=6
v = 2;
p = 1:.1:20;
t = ((p./6) + (sqrt(b^2 + (a - p.)^2)/2))
plot(p,t)

每当我尝试绘制此图时,我都会收到错误消息。 错误是, 不平衡或意外的括号或括号。

但我已经检查了多次,我没有不平衡的括号。我相信这个错误与元素矩阵乘法有关。

【问题讨论】:

  • 为什么将t定义为符号变量?最后一行的下一行也有语法错误
  • “一个错误”? “错误:计算机着火了!”。解决这个问题的方法是灭火器。我的观点:告诉我们错误
  • 你的意思是sqrt(b^2 + (a^2 - p.^2))
  • 我进行了编辑...应该是 (a - p.)^2。
  • 标量/矩阵乘法将每个矩阵元素乘以标量。逐元素矩阵/矩阵乘法需要一个点。请参阅我的答案和链接文档。

标签: matlab


【解决方案1】:

更正的代码,删除了无效的额外内容:

a = 10;
b = 10;
p = 1:0.1:20;
t = p/6 + sqrt( b^2 + (a - p).^2 )/2;
plot(p,t)

关于逐元素操作的说明:

当矩阵的相应元素之间发生某些事情时,您只需使用点 . 运算符来强制执行元素操作。

例如,要获取[1 * 2, 3 * 4],您可以这样做

[1, 3] .* [2, 4]

但是,对于[6 * 1, 6 * 2],您可以这样做

6 * [1, 2]

没有点。没有区别,但值得始终牢记您实际尝试做的事情!

例如,您的原始行是

t = ((p./6) + (sqrt(b^2 + (a - p.)^2)/2))

以下是我如何更改它的步骤

% no need for element-wise division for scalar 6
t = ((p/6) + (sqrt(b^2 + (a - p.)^2)/2))
% the dot after p does worse than nothing, it causes an error
t = ((p/6) + (sqrt(b^2 + (a - p)^2)/2))
% you need a dot to achieve element-wise squaring of the vector (a-p)
t = ((p/6) + (sqrt(b^2 + (a - p).^2)/2))  
% by the order of operations, you can remove extra bracketing to make bracket errors easier to diagnose
t = p/6 + sqrt(b^2 + (a - p).^2)/2        

文档:

数组与矩阵运算:http://uk.mathworks.com/help/matlab/matlab_prog/array-vs-matrix-operations.html

操作顺序:https://uk.mathworks.com/help/matlab/matlab_prog/operator-precedence.html

【讨论】:

  • 谢谢你。这很有意义。非常感谢您的帮助
  • @muhe 不用担心,很高兴听到 :) 单击此答案左上角的白色/绿色勾号以接受它:)
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多