【问题标题】:MatLab - Loop through X and Y to calculate ZMatLab - 通过 X 和 Y 循环计算 Z
【发布时间】:2015-09-28 12:48:58
【问题描述】:

我正在尝试遍历一些对数空间来计算 Z 值并创建等高线图。但我被困住了。现在我有了 Z 值,如何创建等高线图?我怎样才能设置我的 Z 变量?我对 Z 的计算是基于图像的,我无法以其他方式进行。

X = logspace(-10,0,10);
Y = logspace(-10,0,10);
for x = X
    for y = Y
        % here should some magic happen... but you have to assign real positive integers as indices for z
        z(x, y) = 1; % some other heavy calculation
    end
end

% what should I do here?
contourf(x, y, z); % does not work unfortunately

【问题讨论】:

  • 并不是说您可能希望将事物计算为 X 和 Y 的函数。例如,您可以只说 Z = X.^3-2*log(Y); 并从 X 和 Y 计算 Z 元素。
  • 换句话说:如果可能的话,设计你的函数,让它在矩阵上运行!那你就不需要for循环了,直接写Z = f(X,Y)就行了,一般比较快。
  • 确实如此,但在计算 20 对不同 X 和 Y 值的图像对的平均相关性时会变得更加复杂。

标签: matlab


【解决方案1】:

这行得通吗?

X = logspace(-10,0,10);
Y = logspace(-10,0,10);
for x = 1:numel(X)
    for y = 1:numel(Y)
        %// Note the reversed y,x - this is because the x-axis in an image / chart is usually mapped to the horizontal axis which is the columns whereas matrix representations would have dimension one as the rows. Hence you need to put x in dimension 2 and y in dimension 1
        z(y,x) = 1; %// i.e. z(y,x) = f(X(x), Y(y))
    end
end

contourf(X, Y, z);

【讨论】:

  • 是的,它几乎做到了:)!它现在给出以下抱怨:X 的大小必须与 Z 的大小或 Z 的列数匹配。其中 $X$ 具有 $numel(X)=2$,$Y$ 具有 $numel(Y)= 3$ 和 $Z$ 有 3 列和 2 行。
  • @Kevin 尝试我的编辑 - 我刚刚在分配给 z 时切换了 x 和 y
  • 谢谢!有用 :)!现在我必须等待 30 分钟才能看到结果 :)。
  • 双循环需要很多时间,您可能想尝试对这个问题进行矢量化,或者,如果已经优化实现,则并行处理。尤其是在不得不等待 30 分钟的情况下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
相关资源
最近更新 更多