Given the variables how can i repeat a formula multiple times
    9 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
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 Commenti
Risposte (2)
  KSSV
      
      
 il 18 Lug 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 Commenti
  Adam
      
      
 il 18 Lug 2016
        
      Modificato: Adam
      
      
 il 18 Lug 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 Commenti
Vedere anche
Categorie
				Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


