MATLAB Simple addition of vectors of different lengths

  • Thread starter Thread starter binbagsss
  • Start date Start date
  • Tags Tags
    Addition Vectors
Click For Summary
The discussion revolves around creating a function to add vectors of different lengths with a specified shift, where unaligned elements are treated as zero. The user encounters an error when attempting to call the function with vectors in different orders, leading to confusion about the function's variable definitions and control flow. There is a concern regarding the use of undefined variables 'a' and 'input' within the function, which should instead utilize the parameters 'y' and 'b'. Additionally, questions arise about the logic of the for loop executing despite the first condition not being met. The conversation emphasizes the importance of properly defining function parameters and ensuring consistent variable usage to avoid errors.
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?
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K