使用公式和值阵列填充MATLAB数组

发布于 2025-01-17 12:10:20 字数 364 浏览 2 评论 0原文

我想使用公式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 技术交流群。

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

发布评论

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

评论(1

负佳期 2025-01-24 12:10:20

看起来您的原始循环中有一个错误:
您使用了 i 索引两次:m_1*x(i) + m_2*y(i)^2

结果是 z 矩阵的所有列都相同。

要应用公式 z(i, j) = 2*x(i) + 3*y(j)^2,请使用以下循环:

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(j)^2;
    end
end

要使用一行实现上述循环,我们可以使用首先meshgrid

将循环替换为:

[Y, X] = meshgrid(y, x);
Z = m_1*X + m_2*Y.^2;

对于扩展,请阅读 meshgrid 的文档,它比我可以编写的任何扩展都要好得多...


以下命令给出与原始循环相同的输出(但可能不相关):

Z = repmat((m_1*x + m_2*y(1:length(x)).^2)', [1, length(y)]);

测试:

max(max(abs(Z - z)))

ans =

     0

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:

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(j)^2;
    end
end

For implementing the above loop using one line, we may use meshgrid first.

Replace the loop with:

[Y, X] = meshgrid(y, x);
Z = m_1*X + m_2*Y.^2;

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):

Z = repmat((m_1*x + m_2*y(1:length(x)).^2)', [1, length(y)]);

Testing:

max(max(abs(Z - z)))

ans =

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