How to vectorize this for loop
1 view (last 30 days)
Show older comments
Hey guys, I'm having trouble to vectorize my for loop. I'm basically getting the values of 4 columns and multiplying by the values of another matrix's column. Then storing them in another column of the first matrix
i = 1:length(Bundle);
Bundle(i+n,6) = (Bundle(i,1))*cost_bundle1 + (Bundle(i,2)*cost_bundle2) + ...
(Bundle(i,3)*cost_bundle3) + (Bundle(i,4)*cost_bundle4); %cost per account
Bundle(i+n,7) = seguranca*tax*((Bundle(i,1)*venda_bundle1) + (Bundle(i,2)*venda_bundle2) + ...
(Bundle(i,3)*venda_bundle3) + (Bundle(i,4)*venda_bundle4));%revenue per account
Caixa(i+n,1) = Bundle(i+n,6) + cost; %total cost
Caixa(i+n,2) = Bundle(i+n,7); %total revenue
Caixa(i+n,3) = (Caixa(i+n,2)- Caixa(i+n,1)); %profit
2 Comments
dpb
on 17 Jul 2020
Glad to help...it's always easier when there's enough info to at least have an idea of what's attempted to be being done... :)
Accepted Answer
dpb
on 16 Jul 2020
Edited: dpb
on 17 Jul 2020
Bundle(:,6)=sum(Bundle(:,1:4).*cost_bundle,2); % cost per account
Bundle(:,7)= seguranca*tax*(sum(Bundle(:,1:4).*venda_bundle,2); % revenue per account
Caixa=[Bundle(:,6) Bundle(:,7) Bundle(:,7)-Bundle(:,6)); % cost, revenue, profit
Not knowing the point of the n offset that didn't seem to make much sense, above uses the original height of the BUNDLE array.
NB: Put the cost and sale price values into arrays by column matching the columns of the Bundle array instead of using sequentially numbered variables -- there's where you broke any chance to vectorize as written originally. That's a key in using MATLAB efficiently.
1 Comment
dpb
on 16 Jul 2020
It's also possible to not augment the Bundle array at all but just compute Caixa directly. Then you can also remove the column subscripting...
Caixa=[sum(Bundle.*cost_bundle,2) seguranca*tax*(sum(Bundle(:,1:4).*venda_bundle,2)];
Caixa=[Caixa Caixa(:,2)-Caixa(:,1)];
Also, this would seem to be a place where a MATLAB TABLE() could be very useful data storage option instead of just arrays.
More Answers (1)
dpb
on 16 Jul 2020
Edited: dpb
on 16 Jul 2020
i = 1:length(Bundle);
Bundle(i+n,6) = (
Presuming Bundle is taller (more rows) than wide (columns), the above unless n=0 will have an out-of-bounds error.
NB: length is a VERY dangerous function on arrays as it returns (as is documented)
length(x) --> max(size(x))
so you can get either rows or columns as the max size. Use the size() function with the wanted dimension index to return rows or columns.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!