How to rediagonalize the diagonal of a matrix?

조회 수: 1 (최근 30일)
Paul Wolfram
Paul Wolfram 2016년 10월 10일
편집: Paul Wolfram 2016년 10월 10일
Hello,
I have a 5x5 matrix, V1, with values and a classification in both the first row and first column. If you wanted to, you could think of sectors in an economy that have a classification. The first two sectors have a 3-digit classification, the last two have a 4-digit classification.
V1 =
0 101 111 1234 1111
101 4 0 7 0
111 5 8 0 0
1234 6 0 6 2
1111 0 0 4 9
Now, I want to rediagonalize all columns that have a 4-digit code. That means in four-digit columns the values should be summed up over the whole column and shifted to the diagonal. In particular, the code should perform the following steps:
1. If the classification code has four digits AND the classification code is equal in both the first row AND the first column, then sum up the whole column (excl. the first value of the column, which is the classification code itself)
2. Elseif the classification code has three digits in the column, then leave the value as is
3. Else assign a zero.
The resulting matrix should look like this:
V1 =
0 101 111 1234 1111
101 4 0 0 0
111 5 8 0 0
1234 6 0 17 0
1111 0 0 0 11
I have tried the following code, but it didn't work:
[vrow vcol] = size(V1)
for c = 2:vcol;
for r = 2:vrow;
if all([ V1(1,c) == V1(r,1), numel(num2str(V1(1,c))) > 3, numel(num2str(V1(r,1))) > 3 ]) ;
V1(r,c) = sum(V1(2:end,c)) ;
elseif numel(num2str(V1(1,c))) == 3;
V1(r,c) = V1(r,c);
else
V1(r,c) = 0;
end
end
end
With the above code, I got the following result, which is sort of close to the desired result, only the column summations do not work yet:
V1 =
0 101 111 1234 1111
101 4 0 0 0
111 5 8 0 0
1234 6 0 10 0
1111 0 0 0 9
Thank you for any hints!

채택된 답변

LauraLee Austin
LauraLee Austin 2016년 10월 10일
Hi Paul, You are over writing the matrix V1, therefore you are not summing values from the original matrix. Use a temporary variable name.
[vrow vcol] = size(V1)
for c = 2:vcol;
for r = 2:vrow;
if all([ V1(1,c) == V1(r,1), numel(num2str(V1(1,c))) > 3, numel(num2str(V1(r,1))) > 3 ]) ;
V1tmp(r,c) = sum(V1(2:end,c)) ;
elseif numel(num2str(V1(1,c))) == 3;
V1tmp(r,c) = V1(r,c);
else
V1tmp(r,c) = 0;
end
end
end
V1 = V1tmp;
clear V1tmp
  댓글 수: 1
Paul Wolfram
Paul Wolfram 2016년 10월 10일
편집: Paul Wolfram 2016년 10월 10일
Laura,
thank you for your quick response. Yes, exactly I figured it out in the meanwhile but it is good to know that you can confirm my idea. Thank you very much again! Paul

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by