How to vectorize this for loop
显示 更早的评论
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 个评论
Enzo Tessaro
2020-7-16
dpb
2020-7-17
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... :)
采纳的回答
更多回答(1 个)
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!