# Given the variables how can i repeat a formula multiple times

15 views (last 30 days)

Show older comments

##### 0 Comments

### Answers (2)

KSSV
on 18 Jul 2016

N = 100 ;

a = rand(N,1) ; % random a

b = rand(N,1) ; % randon b

c = zeros(N,1) ; % initialize c which a*b

% using loop

for i = 1:N

c(i) = a(i)*b(i) ;

end

% vectorization

cv = a.*b ;

##### 0 Comments

Adam
on 18 Jul 2016

Edited: Adam
on 18 Jul 2016

For a start, lose the variables a_1, a_2, etc. Use an array, a, of all of them. Likewise with b and the same with the result in c, then it is easy:

function c = calculateStuff( a, b )

c = a .* b;

end

This is vectorisation (or vectorization for Americans) and allows you to calculate the result on all your values far more quickly than if you called the function once in a for loop for every one of your variables.

Obviously this is so simple it doesn't need to be in a function as it is just a one-liner so feel free to just put the code where you need it instead.

Someone can probably post links to well-known places telling you why millions of named variables are bad, but I can never remember where to find it so until then just trust me - Use vectors, it is what Matlab is based around!

##### 0 Comments

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!