Given the variables how can i repeat a formula multiple times
조회 수: 17 (최근 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!