Bad practice to be concentrating size less than or equal to size 0 vectors???

2 views (last 30 days)
I'm trying to create a function that adds two arrays of different sizes. In order to do so, I need to concatenate zeros in front of the smaller array. They each represent the coefficients of a polynomial so they will only have one row. I only needed to find the column difference.
The first method I came up with was:
function ap = add_poly(R, S)
% Find the size difference between the two vectors
vec_dif = size(R) - size(S);
% If size of R is bigger than S, vec_dif(2) will be positive
% If size of S is bigger than R, vec_dif(2) will be negative
if vec_dif(2) > 0
% Concatenate zeroes to the beginning of S
S = [zeros(1,vec_dif(2)),S];
elseif vec_dif(2) < 0
% Concatenate zeroes to the beginning of R
%
% Important!: Change negative vec_dif(2) value to
% positive
R = [zeros(1,-vec_dif(2)),R];
end
ap = R + S;
end
After some thought I came up with a shorter method:
function ap = add_poly(R, S)
% Find the size difference between the two vectors
vec_dif = size(R) - size(S);
%Add vectors of equal dimensions
ap = [zeros(1,vec_dif(2)),S] + [zeros(1,-vec_dif(2)),R];
end
In this method, I would be calling the function "zeros" that attempts to create a vector with negative dimensions, such as 0 x -2. But it works since if the dimensions are negative, MatLab won't Concatenate anything.
My question is: is this bad practice? Should I just stick with my original method that doesn't attempt to create a vector with negative dimensions? Can you suggest any alternative that is better than both?

Answers (1)

Stephen23
Stephen23 on 3 Oct 2015
Edited: Stephen23 on 4 Oct 2015
The second shorter method is much better, and is the more MATLAB-y solution.
There is no problem with calling zeros with negative values, as the documentation explicitly states that these are simply treated as being zero: "If the size of any dimension is negative, then it is treated as 0."
Your code calling zeros with negative values is a convenient application of this documented feature, and not at all bad practice. Why do you think this is bad practice? It produces no warning messages, and does not contradict any MATLAB or generic programming best practice that I can think of.
However there are aspects of your code which should be improved:
  • check that the input arguments are vectors of the required orientation
  • using numel rather than size
These are recommended because currently the function behavior may be unexpected when the inputs are column vectors or matrices or N-D arrays.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!