1

The following function has two vector inputs. It appends vector 2 below 1 to make matrix, if vectors have unequal length it adds zeros to the shortest. I've commented out the form that doesn't work, the form that does work is left in. Why does it only work this way round?

function mmat = makemat(vector1,vector2)

diffv = length(vector1)-length(vector2);

% if sign(diffv) 

%     addi = zeros(1,diffv);

%     vector2 = [vector2 addi];

% elseif sign(diffv)== -1

%     addi = zeros(1,abs(diffv));

%     vector1 = [vector1 addi];

if sign(diffv) == -1

    addi = zeros(1,abs(diffv));

    vector1 = [vector1 addi];

elseif sign(diffv)

    addi = zeros(1,diffv);

    vector2 = [vector2 addi];

else

end

mmat = [vector1;vector2];

end
4

1 回答 1

2

That's because if x, with x any nonzero real number, evaluates to true. So if -1 is the same as if 1. When diffv is negative, if sign(diffv) gives true, and addi is wrongly computed as addi = zeros(1,diffv) where diffv is negative. This gives an empty addi, which is wrong.

In the other part of the code no error occurs because the negative case is correctly ruled out first (if sign(diffv) == -1). Even though the last elseif sign(diffv) should be elseif sign(diffv)==1, in this case it works as expected, because at that point the variable diffv can only be positive.

So: change all if/elseif conditions in your code to: sign(diffv)==1 or sign(diffv)==-1


As a side note, you could define your function more easily as follows:

function mmat = makemat(vector1, vector2)

mmat = vector1;
mmat(2,1:length(vector2)) = vector2;

This works because Matlab automatically fills with zeros. In the last line the second index cannot be : in case vector2 is shorter.

于 2013-10-14T23:24:31.883 回答