# Vectorization of for loop

1 view (last 30 days)
Safwana Razak on 15 Jul 2021
Answered: Jayant Gangwar on 15 Jul 2021
B = randi(10x5);
x = randi(10x40);
y = randi(10x1);
% Modelfun = equation to fit
% I can do a for loop like this:
for i=1:10
[beta(i,:)]=nlinfit(x(i,:),y(i,:),modelfun,B)
end
Can I do vectorization? for example 10 fittings all at once, without using loops? or maybe using @cellfun or @arrayfun?
KSSV on 15 Jul 2021
cellfun, arrayfun also uses loop inside...

Jayant Gangwar on 15 Jul 2021
It seems to me that you want to avoid the use of loops for finding all the rows of beta, You can do it by directly passing the complete x matrix and y vector to the nlinfit function, It will automatically save the answer in different rows of beta. An example of the same is given below-
X = S.reactants; % 13x3 matrix
y = S.rate; % 13x1 vector
beta0 = S.beta;
[beta,R,J,CovB,MSE,ErrorModelInfo] = nlinfit(X,y,@hougen,beta0,'ErrorModel','combined');
beta
This is an example given in the documentation for nlinfit, for more information please take a look at the documentation for nlinfit - Nonlinear regression - MATLAB nlinfit (mathworks.com)

R2021a

### Community Treasure Hunt

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

Start Hunting!
{"ft_lang_label":"__label__en","ft_lang_prob":0.88949585,"math_prob":0.8786284,"size":286,"snap":"2021-43-2021-49","text_gpt3_token_len":63,"char_repetition_ratio":0.09219858,"word_repetition_ratio":0.0,"special_character_ratio":0.20979021,"punctuation_ratio":0.05,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9791671,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-25T16:17:35Z\",\"WARC-Record-ID\":\"<urn:uuid:ccf531dc-f25f-4ad9-bf9e-b31f70a49892>\",\"Content-Length\":\"111388\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:abbfa2ef-90f5-48a3-bdf1-4021e9c867b6>\",\"WARC-Concurrent-To\":\"<urn:uuid:9f44e7ed-8f3c-4264-9c1b-9accccbbd92a>\",\"WARC-IP-Address\":\"184.25.188.167\",\"WARC-Target-URI\":\"https://ch.mathworks.com/matlabcentral/answers/879173-vectorization-of-for-loop\",\"WARC-Payload-Digest\":\"sha1:4YBUVXMQKW7DRAJD77SDIDVJ5DDNQUPU\",\"WARC-Block-Digest\":\"sha1:O24N27UIAFX3MOUM53G7BCXQULB7LRAN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323587719.64_warc_CC-MAIN-20211025154225-20211025184225-00532.warc.gz\"}"}