Given the variables how can i repeat a formula multiple times
15 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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 ;
0 个评论
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!
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!