# How to add vector from cell?

2 views (last 30 days)
Machine Learning on 4 Feb 2015
Edited: Stephen23 on 5 Feb 2015
Hi,
I have store my vector into cells and now I want to add them all up. How do I go about doing it?
for i=1:5
Y{i}=randn(10,1); %The vector I want to add
X{i}=randn(5,10); %The matrix that associate with the vector
Z{i}=X{i}*Y{i};
end
total=Y{1}+Y{2}+Y{3}+Y{4}+Y{5};
Is there a faster way to do it? Because the number of loop I run can be quite big.
Or is there a better way to store the vector? I choose to store it in cell is because I have to assign matrix to the same vector as well.
Stephen23 on 5 Feb 2015
Edited: Stephen23 on 5 Feb 2015
Good points. I had a look around and found a few references to other discussions on this. I posted a new question to try and find out what other Answers users think, and if there is some kind of consensus on how to deal with these two variable names.

Michael Haderlein on 4 Feb 2015
Yes:
sum(cat(3,X{:}),3)
the same for Y and Z.
Comment: I have chosen to use the third dimension as this is not existing in any cell before.
##### 2 CommentsShowHide 1 older comment
Stephen23 on 4 Feb 2015
Edited: Stephen23 on 4 Feb 2015
One of the biggest benefits to using MATLAB is the great IDE and the comprehensive help . For example, when you are in the MATLAB command window you can type the following:
doc cat
to bring up the help documentation for the function cat . You can also display the help text directly in the command window with
help sum
Tip for beginners: open the help and look at the left-hand side of the page. There you will see a very useful box entitled "Contents". You can use this to navigate around the documentation, it is great for discovering related functions, examples for particular data classes, and ton of other handy stuff that makes your life a lots easier. Spend a few minutes exploring "Contents" and get used to using it when you are writing your code. From the "Contents" you should be able to locate the page for cell-array indexing , for example.