matlabmatrixdot-operator

Is there any comparation operator applied for matrixs in Matlab, like the dot operator '.*', './', '.^'


I have function f like this

function z=f(x,y)
    if(x<1 & y <1)
        z=0;
    else
        z=1;
    end
 end 

And a script

x=0:0.1:2;
y=0:0.1:2;
[X,Y]=meshgrid(x,y);
Z=f(X,Y);
mesh(X,Y,Z);

When running this script, I got this errors: Z must be a matrix, not a scalar or vector.

It's because x and y here are two arrays, not scalar value. The script can run if I change the

function f looks like this:
     function z = f( x,y )
     for i=1:size(x,2)
         for j=1:size(y,2)
             if(x(i)<1 & y(j)<1)
                 z(i,j)=0;
             else
                 z(i,j)=1;
             end
         end
     end
     end

The broblem is that the new function runs much slower than the first one. I don't know if there is any comparation operator applied for arrays in this case, like the ".*" operator used in this function

function z=f(x,y)
    z=x.*y;
 end

Thank you very much.


Solution

  • You're getting an error, because the function f(x,y) returns a scalar for z and mesh expects z to be a matrix. You can replace all of the functions and code above with a simple, fast vectorized solution, that uses logical indexing:

    x=0:0.1:2;
    y=0:0.1:2;
    [X,Y]=meshgrid(x,y);
    Z=ones(size(X));
    Z(X(:)<1&Y(:)<1)=0;
    
    mesh(X,Y,Z)
    

    This produces the following figure

    enter image description here