How to vectorize this for loop
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
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... :)
採用された回答
dpb
2020 年 7 月 16 日
編集済み: dpb
2020 年 7 月 17 日
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 件のコメント
dpb
2020 年 7 月 16 日
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.
その他の回答 (1 件)
dpb
2020 年 7 月 16 日
編集済み: dpb
2020 年 7 月 16 日
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 件のコメント
参考
カテゴリ
Help Center および 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!