Simple addition of vectors of different lengths

  • Topic: MATLAB 
  • Thread starter Thread starter binbagsss
  • Start date Start date
  • Tags Tags
    Addition Vectors
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
2 replies · 2K views
binbagsss
Messages
1,291
Reaction score
12
I want it to be able to add vectors of different length with a 'shift' of c, and where elements do not align to assume a zero in the place of that,

My function is:

Matlab:
%c is the parameter shift
function[sum]=vecadd(y,b,c)

p=length(input)
q=length(a)

if p > q
for i= 1+delay:p+delay
    input(1+delay:p-delay)=input+a
    break
end
    elseif q>p
    for i= 1+delay:q+delay
    a(1+delay:q-delay)=input+a(1+delay:q-delay)
    break
   
   
    end
<Moderator's note: please use code tags when posting code.>I have tested on the vectors y=[ 1 2 3 4] and b= [1 2 3 4 5 6 7 8].

vecadd(y,b,c) works whereas the order vecadd(b,y,c) does not and it comes up with the error:
"Matrix dimensions must agree. Error in vecadd (line 9) input(1+c:p-c)=input+a"

However, it should not be carying out that for loop I thought, the first for loop, since the first if statement is not true, and it should just be skipping to the next elseif statement? why is this for loop being carried out still?

Many thanks !
 
Last edited by a moderator:
Physics news on Phys.org
Your function has arguments y, b and c, but then you start doing stuff on a and input. Where are these defined? I might just be really bad at reading Matlab code...
 
Office_Shredder said:
Your function has arguments y, b and c, but then you start doing stuff on a and input. Where are these defined? I might just be really bad at reading Matlab code...
I don't think so. No matter which programming language one uses, the inputs to a function should be in its parameter list, not via variables defined outside of the function.

Also, how does sum ever get set?