How to write a MATLAB code to compute a set of indices from an array?

4 views (last 30 days)
I would like to compute a set of indices T={j≠1,2| (1,j) and (j,2) belong to KV for j in {1,2,3,4} }, where
KV = {(4,1), (3,2), (1,3), (2,3), (2,4), (3,4)}. The answer is T = {3}. But I wanted to write a matlab code that gives the answer. To be more precise, form a given matrix B below,
B = [...
1 0 0.6443 0;...
0 1 2.4082 4.6555;...
0 0.6443 1 3;...
0.4152 0 0 1];
KV represents the entries position whose entries are different from 0. Using MATLAB code, we can verify KV as follows.
clear
B = [...
1 0 0.6443 0;...
0 1 2.4082 4.6555;...
0 0.6443 1 3;...
0.4152 0 0 1];
n = max(size(B)); % max size
missingEntries=6; %number of missing entries in B
knownValues = zeros(n*(n-1)-missingEntries,2); %PREALLOCATE
index = 1; % an index that verifies the position of i and j
for j = 1:n
for i = 1:n
if B(i,j) ~= 0 && i~= j
knownValues(index,1) = i; % position of knownValues in the ith row
knownValues(index,2) = j; % position of knownValues in the jth column
index = index+1; % update index until (A(i,j) == 0) ends
end
end
end
knownValues;
KV = knownValues
KV = 6×2
4 1 3 2 1 3 2 3 2 4 3 4
But I got stuck to compute a set of indices T = { j≠1,2 such that both pairs (1,j) and (j,2) belong to KV for j in {1,2,3,4} }, where
KV = {(4,1), (3,2), (1,3), (2,3), (2,4), (3,4)} using MATLAB. The answer is T = {3}. But I wanted to write a matlab code that gives this answer.
I wonder if you could assist me.
Thanks in advance.

Accepted Answer

Matt J
Matt J on 6 Dec 2021
Edited: Matt J on 6 Dec 2021
B = [...
1 0 0.6443 0;...
0 1 2.4082 4.6555;...
0 0.6443 1 3;...
0.4152 0 0 1];
n=size(B,1);
B(1:n+1:end)=0;
[i,j]=find(B);
T=setdiff( intersect(j(i==1),i(j==2)) ,[1,2])
T = 3
  3 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!