Can anyone please vectorize the code I have?

1 回表示 (過去 30 日間)
Nadatimuj
Nadatimuj 2022 年 5 月 14 日
コメント済み: Bruno Luong 2022 年 5 月 14 日
Input
J_org =
0 2 0 1 0 -1 -1
2 0 0 -1 -1 3 0
0 0 0 -2 0 1 1
1 -1 -2 0 2 0 0
0 -1 0 2 0 0 1
-1 3 1 0 0 0 0
-1 0 1 0 1 0 0
J_upper = triu(J_upper);
J_indices = [ 0 1 0 2 0 3 4
0 0 0 5 6 7 0
0 0 0 8 0 9 10
0 0 0 0 12 0 0
0 0 0 0 0 0 13
0 0 0 0 0 0 0
0 0 0 0 0 0 0]
Output:
J_out =[ 2 1 -1 -1 -1 -1 3 -2 1 1 0 2 1 0]
output J_out should be a flattened 1D vector where J_out(J_indices ) should be corresponding value from J_upper. If a J_index is missing (for example, 11 and 14 in my example), the value of that J_out will be zero. Length(J_out) should be ceil(0.5*length(J_org)*max(degree(graph(J_org)))). Here is my version of the code:
J_out = zeros(1,ceil(0.5*length(J_org)*max(degree(graph(J_org)))));
for i = 1:length(J_org)
for j =1:length(J_org)
if J_indices(i,j)
J_out (J_indices(i,j))= J_upper(i,j);
end
end
end

採用された回答

Bruno Luong
Bruno Luong 2022 年 5 月 14 日
編集済み: Bruno Luong 2022 年 5 月 14 日
There is nothing in your data to guess that Jout must have 14 elements, the last index > 0 is 13.
J_org = [
0 2 0 1 0 -1 -1
2 0 0 -1 -1 3 0
0 0 0 -2 0 1 1
1 -1 -2 0 2 0 0
0 -1 0 2 0 0 1
-1 3 1 0 0 0 0
-1 0 1 0 1 0 0]
J_org = 7×7
0 2 0 1 0 -1 -1 2 0 0 -1 -1 3 0 0 0 0 -2 0 1 1 1 -1 -2 0 2 0 0 0 -1 0 2 0 0 1 -1 3 1 0 0 0 0 -1 0 1 0 1 0 0
J_upper = triu(J_org);
J_indices = [ 0 1 0 2 0 3 4
0 0 0 5 6 7 0
0 0 0 8 0 9 10
0 0 0 0 12 0 0
0 0 0 0 0 0 13
0 0 0 0 0 0 0
0 0 0 0 0 0 0]
J_indices = 7×7
0 1 0 2 0 3 4 0 0 0 5 6 7 0 0 0 0 8 0 9 10 0 0 0 0 12 0 0 0 0 0 0 0 0 13 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Jut=J_upper.';
Jit = J_indices.';
b=Jit>0;
Jout = zeros(1,14); % or J_out = zeros(1,ceil(0.5*length(J_org)*max(degree(graph(J_org)))))
Jout(Jit(b)) = Jut(b)
Jout = 1×14
2 1 -1 -1 -1 -1 3 -2 1 1 0 2 1 0
  2 件のコメント
Nadatimuj
Nadatimuj 2022 年 5 月 14 日
編集済み: Nadatimuj 2022 年 5 月 14 日
@Bruno Luong Thanks for the quick answer. It's just a requirement for hardware purpose that the length of J_out must be an even number, although I agree it is invisible in the data. Thanks.
Bruno Luong
Bruno Luong 2022 年 5 月 14 日
@Nadatimuj You are welcome, if it helps could you accept the answer?

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by