Search code examples
matlabmatlab-guidematlab-deployment

Conversion function for 3D value into 2D in MATLAB


I have written a function for converting 3D values into 2D, but not able to get it working may be I am parsing the wrong values.

I am passing the value in the valuse as 2 coordinates and trying to get into Output in 2D. Can anyone please do the correction in the function below and help me in running the function?

% Perspective Projection
function Output = perspective_projection(Input)
 Output = zeros(size(Input));
 for ii = 1: length(Input)
  Output(ii,1) = Input(ii,1)/Input(ii,3);
  Output(ii,2)=Input(ii,2)/Input(ii,3);
 end


value = [6,4,2];
[a1,b1] = perspective_projection(a1)

Solution

  • If I understand you correctly, you should rewrite your function as:

    function Output = perspective_projection(Input)
        Output = bsxfun(@rdivide, Input(:,1:2), Input(:,3)); 
    end
    

    or, judging from the way you seem to be calling it:

    function [OutputX,OutputY] = perspective_projection(Input)
        OutputX = Input(:,1)./Input(:,3); 
        OutputY = Input(:,2)./Input(:,3); 
    end
    

    Note that your function is quite simple (I wouldn't even use a function):

    [X,Y] = deal(Input(:,1)./Input(:,3), Input(:,2)./Input(:,3)); 
    

    As for your original function: the error is in the initialization:

    function Output = perspective_projection(Input)
    
        %// WRONG: this initializes a 3D array!
        Output = zeros(size(Input));
    
        %// ...but you want a 2D array
        for ii = 1: length(Input)
            Output(ii,1) = Input(ii,1)/Input(ii,3);
            Output(ii,2) = Input(ii,2)/Input(ii,3);
        end
    
    end
    

    and of course, the multiple outputs (but it's not quite clear to me whether you want that or not...)