The calculation of matrices is one of the most difficult numerical computation tasks. You may need to add values diagonally in a table when performing mathematical computations. Excel allows you to sum diagonal numbers without having to add the values one by one. We’ll go through how to sum cells diagonally down or diagonally up.
Example: The image below shows a matrix & we want to add the elements of the diagonal. Diagonal1 is the right diagonal & Diagonal2 is the left diagonal as its top element is on the left.
Conditional Formatting (On Matrix or Table) :
To do conditional formatting use the following steps :
Step 1: Select the Matrix/Table. Then Go to the home tab & select the conditional formatting option.
Step 2: Choose New Rule.
Step 3: Select: “Use a formula to determine which cells to format” & in the rule description give the format values for the formula. Here we give 1st cell name of the matrix in the formula, i.e., column(B2) – row(B2) (For diagonal)
Step 4: Click on the format. Choose the color, fonts, etc, for formatting & then click on OK.
Step 6: Click on Ok.
You will get your cells formatted.
How to Sum Diagonal Cells in a range in Excel?
A range of cells containing values can be seen in the image below :
Steps to sum the elements diagonally down(from top to bottom) :
Check the cell ranges, say, ‘B2’ is the first upper-left cell. This is significant because cell ‘B2’ serves as the start point for the diagonal sum. We SUM the diagonal values down from the first cell ‘B2’ diagonally right till ‘E5’.
Here we want right the diagonal sum, i.e., sum of the cells: B2+C3+D4+E5 .
To do sum of the Left diagonal we will use the formula :
=SUM((COLUMN(Cells Reference)-ROW(Cells Reference) =cellName )*Cells Reference) into a blank cell , Say F6
Step 1: Go to the cell, where you want to get the result of the addition.
Step 2 : There write : =SUM((COLUMN(B2:E5)-ROW(B2:E5)=M1)*B2:E5)
Step 3 : Press Ctrl + Shift + Enter.
You will get the left diagonal sum. Here you can see the left diagonal sum = 1+1+1+1 = 4
Note: Here M1 contains the difference between columns & rows. Currently, in the above image, it is 0.
If we go to M1 & change its value to 2 :
The addition now is changed to 49 which is the sum of D2 + E3 , i.e., 44+5 = 9. The value 2 of M here indicates the diagonal 2 steps above the current diagonal(in other way we exclude 2 columns & 2 rows)
If we go to M1 & change its value to -1 :
The addition now is changed to 74 which is the sum of B3 + C4 + D5 , i.e., 3+4+67. The value -1 of M here indicates the diagonal 1 step below the current diagonal(in other way we exclude 1 column & 1 row downwards)
Steps to sum the elements diagonally up(from bottom) / The SUM of Diagonal Cells Ascending from Left to Right :
Check the cell ranges, say, ‘E2’ is the first upper right cell. This is significant because cell ‘B5’ serves as the start point for the diagonal sum. We SUM the diagonal values down from the first cell ‘E2’ diagonally right till ‘B5’.
Here we want right the diagonal sum , i.e., sum of the cells: E2+D3+C4+B5. To do sum of the right diagonal we will use the formula :
=SUM(Cell Reference*((ROWS(Cell Reference) + Ri)-ROW(Cell Reference)=COLUMN(Cell Reference)-Ci)) into a blank cell , Say F6 Ri => the number of rows in front of the data range's initial cell. Ci => the number of columns in front of the data range's initial cell.
Example 1: If you have a 5*5 matrix from Row 1 & column A (i.e., From A1 to E5), then if we formula :
= SUM(A1:E5*((ROWS(A1:E5)+0)-ROW(A1:E5)=COLUMN(A1:E5)))
Here Ri = 0, then the no of rows in front of the first cell of the data range is 0, so the addition is done for: A4+ B3 + C2 + D1
Example 2 :
Step 1: Go to the cell, where you want to get the result of the addition.
Step 2 : There write : =SUM(B2:E5*((ROWS(B2:E5)+2)-ROW(B2:E5)=COLUMN(B2:E5)-1))
Step 3 : Press Ctrl + Shift + Enter.
You will get the left diagonal sum. Here you can see the right diagonal sum = 11+14+2+2 = 29
The Diagonal Sum of Values in an Excel table if the number of columns and rows is the same :
In the above example also we have the same number of rows & columns in the cell range. But the thing in the below example differ is that there are different numbers of columns & rows in front of the cell range.
Suppose we want to calculate sum of the elements diagonally up :
Here, Ci = 2 & Ri = 2: as the number of rows in front of the cell reference is 2 & the number of columns in front of the actual cell references is 1.
The Diagonal Sum of Values in the Excel table if the number of columns and rows is different :
In the image below, you can see that the number of rows = 6 & the number of columns = 5 in the cell references.
To find the diagonal sum, follow these steps :
Step 1: Go to the cell, where you want to get the result of the addition.
Step 2: There write : = SUMPRODUCT(((MATCH($A$3:$A$8,$A$3:$A$8,0)-MATCH($B$2:$F$2,$B$2:$F$2,0))=5-4)*($B$3:$F$8))
Step 3: Press Ctrl + Shift + Enter.
Sum of Diagonal Values per column :
The basic formula comes next if we wish to start at the beginning and multiply the total of the numbers or values diagonally by the start column of cell ‘B3’. Take note of the number of rows labeled ‘pink’ in the calculation below.
= SUMPRODUCT(((MATCH($A$3:$A$5,$A$3:$A$5,0)-MATCH($B$2:$D$2,$B$2:$D$2,0))=1-1)*($B$3:$D$5)) = SUMPRODUCT((((ROW($A$3:$A$5)-1)-(COLUMN($B$2:$D$2)-2))=3-1)*($B$3:$D$5))
The Diagonal Sum Down for a specific Number of Columns :
Use the ARRAY formula below to get the sum of the values diagonally down for a certain number of columns. The formula is found in cell ‘I11’ in the image above, while the condition ‘number 3’ is found in cell ‘G11’ in the image above. Only the first 4 columns of the data range are included in this calculation, which is the diagonal sum of values (enter the formula in one line).
= SUM(IF(ROW(OFFSET($B$3:$F$8,0,0,$G$11,G11))-MAX(ROW(OFFSET($B$3:$F$8,0,0,$G$11,G11)))= COLUMN(OFFSET($B$3:$F$8,0,0,$G$11,G11))-MAX(COLUMN(OFFSET($B$3:$F$8,0,0,$G$11,G11))), OFFSET($B$3:$F$8,0,0,$G$11,G11),FALSE))
Note that here, in G11, we are specifying the column up to which we want to sum the diagonal elements.
Когда вы выполняете арифметические вычисления, вам может потребоваться суммировать числа в таблице по диагонали. Фактически, вы также можете суммировать диагональные числа в Excel, что не требует суммирования чисел одно за другим. Если вы хотите узнать больше об этом вопросе, прочтите следующую статью.
Суммирование диагональных ячеек диапазона в Excel
Суммирование диагональных ячеек диапазона в Excel
Предположим, у меня есть следующий диапазон данных, и теперь я хочу получить результат суммирования диагональных ячеек.
1. Суммируйте ячейки по диагонали вниз и вправо.
Если вы хотите просуммировать диагонали ячеек от верхнего левого угла до нижнего правого угла (A1 + B2 + C3 + D4), вам могут помочь следующие формулы.
Пожалуйста, введите эту формулу =SUM(A1:D4*(ROW(A1:D4)=COLUMN(A1:D4))) в пустую ячейку, см. снимок экрана:
Затем нажмите Shift + Ctrl + Enter вместе, и вы получите желаемый результат.
2. Суммируйте ячейки по диагонали вверх и вправо.
Чтобы просуммировать диагональные ячейки от нижнего левого угла до верхнего правого угла (A4 + B3 + C2 + D1), вы должны применить следующую формулу: =SUM(A1:D4*(ROWS(A1:D4)+1-ROW(A1:D4)=COLUMN(A1:D4))), и нажмите Shift + Ctrl + Enter ключи, чтобы получить правильный результат. Смотрите скриншоты:
Заметки:
1. Аргументы А1: Д4 — это диапазон данных, в котором вы хотите просуммировать диагональные ячейки.
2. Эти формулы применяются только к ячейкам диапазона, которые имеют одинаковый номер столбца и номер строки, например 5 столбцов и 5 строк.
Связанная статья:
Как суммировать все цифры числа в Excel?
Лучшие инструменты для работы в офисе
Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%
- Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
- Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон…
- Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны…
- Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
- Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
- Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии…
- Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
- Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF…
- Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Комментарии (6)
Оценок пока нет. Оцените первым!
0 / 0 / 0 Регистрация: 14.10.2015 Сообщений: 3 |
|
1 |
|
Как найти сумму диагональных элементов матрицы?14.10.2015, 21:41. Показов 9145. Ответов 4
Помогите составить формулу в EXCEL, используя функцию «ЕСЛИ» для нахождения суммы диагональных элементов матрицы. Задана квадратная матрица (5X5), которые содержит положительные и отрицательные числа.
0 |
15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
14.10.2015, 23:03 |
2 |
РешениеAigulZel, формула массива — вводится нажатием Ctrl+Shift+Enter, отображается в фигурных скобках Код =СУММ(ЕСЛИ((СТРОКА(A1:A5)=СТОЛБЕЦ(A1:E1))+(6-СТРОКА(A1:A5)=СТОЛБЕЦ(A1:E1));A1:E5))
0 |
0 / 0 / 0 Регистрация: 14.10.2015 Сообщений: 3 |
|
15.10.2015, 21:28 [ТС] |
3 |
По данной формуле вычисляется сумма всех элементов матрицы. А в задаче требуется определить сумму элементов главной диагонали (то есть след матрицы). А каково значение числа 6 в формуле? Вроде и без него ответ такой же получается
0 |
15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
15.10.2015, 22:10 |
4 |
По данной формуле вычисляется сумма всех элементов матрицы Так «диагональных элементов» (#1), т.е. обеих диагоналей, или «главной диагонали» (#3)? Код =СУММ(ЕСЛИ(СТРОКА(A1:A5)=СТОЛБЕЦ(A1:E1);A1:E5)) или обычная формула Код =СУММПРОИЗВ(A1:E5*(СТРОКА(A1:A5)=СТОЛБЕЦ(A1:E1)))
1 |
0 / 0 / 0 Регистрация: 14.10.2015 Сообщений: 3 |
|
16.10.2015, 21:21 [ТС] |
5 |
Спасибо большое, разобралась.
0 |
I’m attempting to sum all the cells diagonally from the corner of a cell within a table so if the cell is A1 i’d want it to show the sum of B2,C3,D4 etc. but dynamically expand with the table so if i added a Column E it would sum in E5 without it needing to be manually altered.
At the moment I am manually adding in the required cells when the table expands but is isn’t sustainable. I’ve used a very reliable sumproduct equation to calculate the diagonal but I can’t get it to maintain the required square matrix with table expansion or exclude the cell its being used in
=SUMPRODUCT((ROW(Table1)-MAX(ROW(Table1))=COLUMN(Table1)-MAX(COLUMN(Table1)))*(Table1))
I can’t work out how to remove the column and row of the cell that the formula is in from from the arrays and this only works for a square table and the top corner. Any other positions within the table return zero and attempts to hardcode and remove the rows which aren’t required cause #VALUE
asked Jan 25, 2019 at 15:19
You could use an array formula. This is an example of the formula to use considering the first 3 rows and columns:
{=SUM(A1:C3*(ROWS(A1:C3)+1-ROW(A1:C3)=COLUMN(A1:C3)))}
In your case you can apply the formula to a large range. If your matrix expands it will include all values in the range, e.g. (for 100)
{=SUM(B2:CY100*(ROWS(B2:CY100)+1-ROW(B2:CY100)=COLUMN(B2:CY100)))}
Note:
For an array formula to work you will need to use Ctrl+Shift+Enter after entering it into the cell. The brackets {} will then be added automatically. You do not type these yourself.
answered Jan 25, 2019 at 16:22
JormundJormund
2031 silver badge14 bronze badges
porrter Пользователь Сообщений: 9 |
вычислить сумму квадатов элементов двумерного массива, расположенных на главной диагонали для матриц |
слэн Пользователь Сообщений: 5192 |
p=1 |
слэн Пользователь Сообщений: 5192 |
почему-то на произведение потянуло.. p=0 p=p+arr(i,i)*arr(i,i) |
porrter Пользователь Сообщений: 9 |
{quote}{login=слэн}{date=02.11.2010 12:50}{thema=}{post}почему-то на произведение потянуло.. p=0 p=p+arr(i,i)*arr(i,i){/post}{/quote} Надо в экселе, вба не всчет. |
слэн Пользователь Сообщений: 5192 |
СУММ(МУМНОЖ(мас;МОБР(мас))*мас*мас) |
слэн Пользователь Сообщений: 5192 |
|
слэн Пользователь Сообщений: 5192 |
СУММПРОИЗВ(МУМНОЖ(мас;МОБР(мас));мас;мас) немассив |
{quote}{login=слэн}{date=02.11.2010 01:22}{thema=}{post}СУММПРОИЗВ(МУМНОЖ(мас;МОБР(мас));мас;мас) немассив{/post}{/quote} можете написать кто нибудь свою аську или скайп.. а то здесь тяжеловато общаться. долгу не останусь |
|
=СУММПРОИЗВ((E8:F9*{1;0:0;1})^2) |
|
{quote}{login=}{date=02.11.2010 01:36}{thema=}{post}=СУММПРОИЗВ((E8:F9*{1;0:0;1})^2) значение недоступно формуле или функции |
|
MCH Пользователь Сообщений: 3875 |
Формула массива |
porrter Пользователь Сообщений: 9 |
{quote}{login=MCH}{date=02.11.2010 02:26}{thema=}{post}Формула массива спасибо большое, все прошло.. MCH, можешь написать свою аську или скайп, просто есть пару вопросов. если тебе конечно не трудно |
vikttur Пользователь Сообщений: 47199 |
#13 19.11.2010 19:26:34 Транспонирование можно убрать: |
Подсчет значений в ячейках по диагонали. |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |