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!