Given the variables how can i repeat a formula multiple times

18 ビュー (過去 30 日間)
fadzhi
fadzhi 2016 年 7 月 18 日
編集済み: Adam 2016 年 7 月 18 日
Hello everybody, I am a newbie to matlab. Would really appreciate some help on this matter. I am looking to solve a formula like c_i = a_i.*b_i. I have to solve it a couple thousand times and for each step,I also need the answer as a variable. The variable a_i and b_i are avaiable like a_1,a_2,a_3,b_1,b_2 ... Regards, Fawad

回答 (2 件)

KSSV
KSSV 2016 年 7 月 18 日
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 ;

Adam
Adam 2016 年 7 月 18 日
編集済み: Adam 2016 年 7 月 18 日
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!

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by