Meshgrid和double for循环不会产生相同的矩阵,为什么? [英] Meshgrid and double for-loops does not result in the same matrix, why?

查看:96
本文介绍了Meshgrid和double for循环不会产生相同的矩阵,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试评估表达式f = 2y-exp(z)对于z和y的不同值可以采用的所有值. y和z是两个长度为M的向量.我想知道为什么生成表达式f的两种方法会产生不同的结果.

I am trying to evaluate all values the expression f = 2y-exp(z) can take for different values of z and y. Were y and z are two vectors of length M. I am wondering why the two approaches for generating the expression f yields different results.

使用网状网格:

    [Y,Z] = meshgrid(y,z);
argument = 2*Y-exp(Z);

并带有双for循环

argument_new = zeros(M,M);
for i = 1:length(y)
    for j = 1:length(z)
    argument_new(i,j) = 2*y(i)-exp(z(j));
    end
end

任何提示将不胜感激!

Any hints will be highly appreciated!

推荐答案

这是因为meshgrid创建反向"方向的原因.我找不到合适的词,但这是一个示例代码示例,您会看到如果取消注释选项2并使用argument_new(j,i)而不是argument_new(i,j),则两个矩阵相等(如通过isequal获得的).

That's because of the way meshgrid creates 'inverted' directions. I don't find the right words, but here is an example illustrating with your code.You see that if you uncomment option 2 and use argument_new(j,i) instead of argument_new(i,j) both matrices are equal (as obtained with isequal).

clear
clc

M = 20;
y = 1:M;
z = 1:M;

[Y,Z] = meshgrid(y,z);
argument = 2*Y-exp(Z);

argument_new = zeros(M,M);
for i = 1:length(y)
    for j = 1:length(z)
    %// 1)    
    argument_new(i,j) = 2*y(i)-exp(z(j));
    %// 2)
    %// argument_new(j,i) = 2*y(i)-exp(z(j));
    end
end

isequal(argument,argument_new) %// Gives 0 for option 1 and 1 for option 2.

这篇关于Meshgrid和double for循环不会产生相同的矩阵,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆