How to add an unknown amount of number in matlab?
4 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (2 件)
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
0 件のコメント
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!