1

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.

Using meshgrid:

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

and with double for-loops

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!

vgdev
  • 57
  • 7
  • [What Luis Mendo said](http://stackoverflow.com/a/27495521/2778484). But here's [my 2 cents](http://stackoverflow.com/a/22461766/2778484). – chappjc Dec 16 '14 at 01:02
  • 1
    so @user3748876 does any of the answer below helped you? If so please mark them as accepted. Thanks! – Benoit_11 Dec 17 '14 at 14:09

3 Answers3

2

Blame that on meshgrid:

MESHGRID is like NDGRID except that the order of the first two input and output arguments are switched (i.e., [X,Y,Z] = MESHGRID(x,y,z) produces the same result as [Y,X,Z] = NDGRID(y,x,z)).

Solution: use ndgrid, which doesn't do that switching, and is thus more "natural":

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

Or in your code, after meshgrid, add a transpose operation: argument = argument.';)

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
2

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.
Benoit_11
  • 13,905
  • 2
  • 24
  • 35
0

They are the same, you should just transpose either one (' in Matlab), or you can replace i by j and vice versa in the for loops

Mihon
  • 125
  • 1
  • 9