Question

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)
Was it helpful?

Solution 2

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...)

OTHER TIPS

BSXFUN method as suggested by Rody is an elegant way, but if you would like to keep your loop, try this -

% Perspective Projection
function Output = perspective_projection(Input)
Output = zeros(size(Input,1),2);
for ii = 1: size(Input,1)
    Output(ii,1) = Input(ii,1)/Input(ii,3);
    Output(ii,2) = Input(ii,2)/Input(ii,3);
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top