使用公式和值阵列填充MATLAB数组
我想使用公式z(i,j)= 2 * x(i) + 3 * y(j)^2在MATLAB中填充10x15矩阵,以便每个条目at(i,j)= z(i,i, J)。我有X和Y的数组,分别为10和15。
我已经使用以下代码完成了任务,但是我想一行完成任务,因为有人告诉我这是可能的。有什么想法吗?
x = linspace(0,1,10);
y = linspace(-0.5,0.5,15);
z = zeros(10,15);
m_1 = 2;
m_2 = 3;
for i = 1:length(x)
for j = 1:length(y)
z(i, j) = m_1*x(i) + m_2*y(i)^2;
end
end
I want to fill a 10x15 matrix in MATLAB using the formula z(i, j) = 2 * x(i) + 3 * y(j)^2, so that each entry at (i, j) = z(i, j). I have arrays for x and y, which are of size 10 and 15, respectively.
I've accomplished the task using the code below, but I want to do it in one line, since I'm told it's possible. Any thoughts?
x = linspace(0,1,10);
y = linspace(-0.5,0.5,15);
z = zeros(10,15);
m_1 = 2;
m_2 = 3;
for i = 1:length(x)
for j = 1:length(y)
z(i, j) = m_1*x(i) + m_2*y(i)^2;
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您的原始循环中有一个错误:
您使用了
i
索引两次:m_1*x(i) + m_2*y(i)^2
。结果是
z
矩阵的所有列都相同。要应用公式
z(i, j) = 2*x(i) + 3*y(j)^2
,请使用以下循环:要使用一行实现上述循环,我们可以使用首先meshgrid。
将循环替换为:
对于扩展,请阅读 meshgrid 的文档,它比我可以编写的任何扩展都要好得多...
以下命令给出与原始循环相同的输出(但可能不相关):
测试:
It looks like you have a bug in your original loop:
You are using
i
index twice:m_1*x(i) + m_2*y(i)^2
.The result is that all the columns of
z
matrix are the same.For applying the formula
z(i, j) = 2*x(i) + 3*y(j)^2
use the following loop:For implementing the above loop using one line, we may use meshgrid first.
Replace the loop with:
For expansions, read the documentation of meshgrid, it is much better than any of the expansions I can write...
The following command gives the same output as your original loop (but it's probably irrelevant):
Testing: