vectorization my user defined function

2 ビュー (過去 30 日間)
Adarsh Tiwari
Adarsh Tiwari 2021 年 12 月 5 日
コメント済み: Adarsh Tiwari 2021 年 12 月 6 日
I have the following array manipulations. How can i convert for loop'for loop' in a Vectorized expression\function.
time =[
5 10
3 5
5 3
5 7
3 5];
cost =[
6 3
4 3
7 10
10 5
14 9];
x=[1 1 1 1 1;2 2 2 2 2;1 2 1 2 1];
Np=size(x,1)
for i=1:Np
fun(i,1:2) = [max([time(1,x(i,1))+time(3,x(i,3))+time(5,x(i,5)),...
time(1,x(i,1))+time(4,x(i,4)),time(2,x(i,2))+...
time(5,x(i,5))]),cost(1,x(i,1))+cost(2,x(i,2))+...
cost(3,x(i,3))+cost(4,x(i,4))+cost(5,x(i,5))];
end
  2 件のコメント
DGM
DGM 2021 年 12 月 5 日
編集済み: DGM 2021 年 12 月 5 日
Off the top of my head, I don't see a simple way to get rid of the loop.
It can be made a bit more compact.
time = [5 10;
3 5;
5 3;
5 7;
3 5];
cost = [6 3;
4 3;
7 10;
10 5;
14 9];
x = [1 1 1 1 1; 2 2 2 2 2; 1 2 1 2 1];
Np = size(x,1);
fun = zeros(Np,2);
for k = 1:Np
tx = diag(time(:,x(k,:)));
fun(k,1:2) = [ max([sum(tx([1 3 5])) sum(tx([1 4])) sum(tx([2 5]))]), ...
sum(diag(cost(:,x(k,:)))) ];
end
fun
I'm sure someone else could come up with something way more clever than I can.
Adarsh Tiwari
Adarsh Tiwari 2021 年 12 月 6 日
Thanks DGM
It is definitely more compact than mine but I needed vectorized form.

サインインしてコメントする。

採用された回答

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2021 年 12 月 5 日
a simple quick solution is :
time =[5,10;3,5;5,3;5,7;3,5];
cost =[6,3;4,3;7,10;10,5;14,9];
x=[1 1 1 1 1;2 2 2 2 2;1 2 1 2 1];
fun = [max([time(1,x(:,1))'+time(3,x(:,3))'+time(5,x(:,5))',...
time(1,x(:,1))'+time(4,x(:,4))',time(2,x(:,2))'+...
time(5,x(:,5))'],[],2),cost(1,x(:,1))'+cost(2,x(:,2))'+...
cost(3,x(:,3))'+cost(4,x(:,4))'+cost(5,x(:,5))']
fun = 3×2
13 41 18 30 13 35
  1 件のコメント
Adarsh Tiwari
Adarsh Tiwari 2021 年 12 月 6 日
It serves my purpose. i may now go ahead with my code.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeApp Building についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by