필터 지우기
필터 지우기

How to find non-zero indexes (or value) in row in matrix, and make taken results i and j elements of another matrix Dij?

조회 수: 1 (최근 30일)
I have a matrix : A =
1 0 0 4
1 0 3 4
1 2 0 4
1 2 3 4
I need to find the non-zero elements in every row of matrix A, and making them i(number of row) and j(number of column) of the matrix Dij(shown below).
Then find that element in matrix Dij, and make summation of values if it needs.
Dij =
0 22.2794 33.7859 45.0000
22.2794 0 15.4008 23.0367
33.7859 15.4008 0 14.9726
45.0000 23.0367 14.9726 0
For example, I need a code which will find all non zero values of every row, results of matrix A should be:
1 4
1 3 4
1 2 4
1 2 3 4
Then the values of every rows should be ij elements of Dij matrix. For example:
1 4==============> D(1,4)=45
1 3 4============> D(1,3)+D(3,4)=33.7859+14.9726
1 2 4============> D(1,2)+D(2,4)=22.2794+23.0367
1 2 3 4==========> D(1,2)+D(2,3)+D(3,4)=22.2794+15.4008+14.9726
Could anyone help me?

채택된 답변

James Tursa
James Tursa 2016년 7월 21일
E.g., using a loop:
m = size(A,1);
result = zeros(m,1);
for k=1:m
x = find(A(k,:));
for n=2:numel(x)
result(k) = result(k) + Dij(x(n-1),x(n));
end
end

추가 답변 (1개)

Stephen23
Stephen23 2016년 7월 21일
편집: Stephen23 2016년 7월 21일
A short version without explicit loops:
>> [Ra,Ca] = find(A~=0);
>> X = accumarray(Ra,Ca,[],@(n){n});
>> F = @(V)arrayfun(@(r,c)Dij(r,c),V(1:end-1),V(2:end));
>> Z = cellfun(@(V)sum(F(sort(V))),X)
Z =
45
48.758
45.316
52.653

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by