Adding 2 different length array

조회 수: 238 (최근 30일)
Uday
Uday 2011년 10월 23일
편집: Azmat Ameen 2020년 12월 17일
I have problem in adding 2 different length array e.g x=[1 2 3 4 5 6 ]', Y =[ 3 5 7 8 ]' Ans= 4 7 10 13 6 but I do not know how to get this answer ? in my code I have tried
dir_list=dir('v1_ch.txt');
vec1=[];
for j=1:12
data=dlmread(dir_list((j-1)*13+k).name,';',3 );
latitude=data(:,1);
longitude=data(:,2);
ch4=data(:,3);
vec1=vec1+ch4; % here I tried to add array together
end
but it does not work ?
  댓글 수: 1
Jan
Jan 2011년 10월 23일
Please edit your question and use the standard code formatting as explained in the "Markup help" link.

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2011년 10월 23일
Arrays have to be the same size (or one has to be a scalar) to add them, otherwise it is ambiguous to MATLAB what should be done with the "leftover" elements.
In your case, you want to pad a zero onto the end of Y, so the addition could be done like this:
x = [1 2 3 4 5 6]';
y = [3 5 7 8]';
A = x + [y;zeros(2,1)];
This will result in A = [4 7 10 12 5 6]'. (This is not exactly what you wrote as your answer, but I am guessing it is what you meant.)
If you don't know ahead of time how many zeros you need to pad at the end, then you can use the size() or length() command to determine the array dimensions, to calculate how many zeros you need.
Finally, you might want to read the "Getting Started" guide. The basics of vector manipulation are covered there.
  댓글 수: 1
Uday
Uday 2011년 10월 23일
Sorry for mistake in typing

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Azmat Ameen
Azmat Ameen 2020년 12월 17일
편집: Azmat Ameen 2020년 12월 17일
function[t,x]=padding(t1,t2,x1,x2)
t=min(min(t1),min(t2)):max(max(t1),max(t2));
y1=zeros(1,length(t));
y2=y1;
y1((t>=min(t1))&(t<=max(t1)))=x1;
y2((t>=min(t2))&(t<=max(t2)))=x2;
x=(y1+y2)
stem(t,x)
end
Use this function to pad zeros and you will get the addition of two different array with different length.

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by