How to add an unknown amount of number in matlab?

조회 수: 10 (최근 30일)
Gennie
Gennie 2014년 10월 20일
편집: Image Analyst 2014년 10월 22일
I am creating a code to get the resultant of an unknown number of vectors by addition. I can't think of a way to add unknown amount of numbers in a loop. Here's my code so far. It only adds two numbers in that kind of equation.
for n=2:1:sv(2)
xx=vect{1,n-1}(1)+vect{1,n}(1)
end

답변 (2개)

David Sanchez
David Sanchez 2014년 10월 20일
Not sure about your intentions, i created a dummy cell and a solution for what i think is your problem:
vect=cell(5,3);% initialization of dummy cell
for r=1:5
for c=1:3
vect{r,c} = rand(3,1); % random 3x1 array in each cell
end
end
%%%the sumation
xx = 0; % initialize summation
for n=1:length(vect(1,:)) % for-loop from first to last (unknown) element
xx = xx + vect{1,n}(1); % iterate along the column
end

David Young
David Young 2014년 10월 20일
The trick is to add on to the result vector each time through the loop.
I don't understand what sv is in your code, and I'm not sure why you select the first element of each vector, so here's a simpler example which adds up all the vectors stored as elements of a cell array, assuming they are all the same size:
% example data
vect = {[1 2 3] [4 5 6] [7 8 9]}; % can have any number of elements
sumVec = 0;
for ii = 1:numel(vect)
sumVec = sumVec + vect{ii};
end
If your initial vectors are stored as the rows or columns of a matrix, it's even simpler - just a single call to the sum() function.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by