

Variables that vary only with respect to i would also be size n x 1 those that vary only with respect to j would be 1 x m and those that vary with respect to both would be n x m. For example, say that i is of size n x 1 and j is of size 1 x m.

But in general the strategy would be to define one of the independent variables as a row vector, and the other as a column vector. Your example relies on enough pre-defined variables (like c, t, etc.) that it was less trivial for me to test. You can measure runtime with various tools, such as tic()/toc() or the profiler.įor your second example, depending on the specifics of your problem it may be easy or difficult. Although since I assume faster runtime is your goal, it might be worth testing a non-vectorized version that calls nchoosek(), just in case there is some optimization voodoo at work there.
#Vectorize matlab code
So if you want your code to be vectorized, it may not be useful to you. I should note that there is a built-in function nchoosek() to do essentially this calculation, and it supports a vector input, but only for the "n" term (which does not vary in your case). This formulation produced the same output as your original form, in my limited testing: i = 1:n Ī2 = (factorial(n-1))./(factorial(i-1).*(factorial(n-i))) In this case that will be fine, but it's unnecessary and in some other cases may not do what you want/expect it's a habit you need to be careful about. The other semi-issue is that you do not need to use the syntax a(i), which will try to assign the entire output array into a subset of a (using i as the indices). The first, as pointed out by Luengo, is that you need to use element-wise division (and also element-wise multiplication). For your first example, there are two issues.
