This matrix is singular ошибка

What does the error Numpy error: Matrix is singular mean specifically (when using the linalg.solve function)? I have looked on Google but couldn’t find anything that made it clear when this error occurs.

strpeter's user avatar

strpeter

2,5023 gold badges26 silver badges48 bronze badges

asked Dec 10, 2012 at 5:47

KaliMa's user avatar

1

A singular matrix is one that is not invertible. This means that the system of equations you are trying to solve does not have a unique solution; linalg.solve can’t handle this.

You may find that linalg.lstsq provides a usable solution.

answered Dec 10, 2012 at 6:09

Michael J. Barber's user avatar

6

This function inverts singular matrices as well using numpy.linalg.lstsq:

def inv(m):
    a, b = m.shape
    if a != b:
        raise ValueError("Only square matrices are invertible.")

    i = np.eye(a, a)
    return np.linalg.lstsq(m, i)[0]

answered May 17, 2017 at 14:02

Procope's user avatar

ProcopeProcope

911 silver badge7 bronze badges

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться в Python:

numpy.linalg.LinAlgError: Singular matrix

Эта ошибка возникает, когда вы пытаетесь инвертировать сингулярную матрицу, которая по определению является матрицей с нулевым определителем и не может быть инвертирована.

В этом руководстве рассказывается, как устранить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, мы создаем следующую матрицу с помощью NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Теперь предположим, что мы пытаемся использовать функцию inv() из NumPy для вычисления обратной матрицы:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

Мы получаем ошибку, потому что созданная нами матрица не имеет обратной матрицы.

Примечание.Ознакомьтесь с этой страницей Wolfram MathWorld, на которой показаны 10 различных примеров матриц, не имеющих обратной матрицы.

По определению матрица сингулярна и не может быть обращена, если ее определитель равен нулю.

Вы можете использовать функцию det() из NumPy для вычисления определителя данной матрицы, прежде чем пытаться ее инвертировать:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

Определитель нашей матрицы равен нулю, что объясняет, почему мы сталкиваемся с ошибкой.

Как исправить ошибку

Единственный способ обойти эту ошибку — просто создать невырожденную матрицу.

Например, предположим, что мы используем функцию inv() для инвертирования следующей матрицы:

import numpy as np
from numpy. linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308 0.26923077]
 [ 0.15384615 -0.03846154]]

Мы не получаем никакой ошибки при инвертировании матрицы, потому что матрица не является единственной.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить: объект numpy.float64 не вызывается
Как исправить: объект ‘numpy.ndarray’ не вызывается
Как исправить: объект numpy.float64 не может быть интерпретирован как целое число


One error you may encounter in Python is:

numpy.linalg.LinAlgError: Singular matrix

This error occurs when you attempt to invert a singular matrix, which by definition is a matrix that has a determinant of zero and cannot be inverted.

This tutorial shares how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following matrix using NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Now suppose we attempt to use the inv() function from NumPy to calculate the inverse of the matrix:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

We receive an error because the matrix that we created does not have an inverse matrix.

Note: Check out this page from Wolfram MathWorld that shows 10 different examples of matrices that have no inverse matrix.

By definition, a matrix is singular and cannot be inverted if it has a determinant of zero.

You can use the det() function from NumPy to calculate the determinant of a given matrix before you attempt to invert it:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

The determinant of our matrix is zero, which explains why we run into an error.

How to Fix the Error

The only way to get around this error is to simply create a matrix that is not singular.

For example, suppose we use the inv() function to invert the following matrix:

import numpy as np
from numpy.linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308  0.26923077]
 [ 0.15384615 -0.03846154]]

We don’t receive any error when inverting the matrix because the matrix is not singular.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix: ‘numpy.float64’ object is not callable
How to Fix: ‘numpy.ndarray’ object is not callable
How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer

Python programming language provides us with various libraries to deal with several numeric, vectorized data and perform operations. Using them prevents us from doing computationally expensive tasks and makes our work easier. One such library is Numpy. It is used to perform mathematical operations on array and matrices. Some of them are cross-multiplication, dot-product, inverse e.t.c. While operating these matrices sometimes, we get errors like LinAlgError Singular Matrix. This article will try to understand the error and find suitable solutions for it.

So, LinAlgError is raised by linear algebra class (named linalg) when some linear algebra function prevents the correct execution of other program parts. The singular matrix is the sub-error raised when we perform incorrect operations on the singular matrix.

What is LinAlgError Singular Matrix Error?

LinAlgError Singular Matrix Error

So, in the above image, you can see that the interpreter threw a LinAlgError: Singular matrix. It means that the error occurred because of some linear algebra operation that is computationally incorrect. Talking more descriptively, we can say that some operations on a singular matrix are because of some operations. The matrix may not support those operations.

Why do I get “LinAlgError Singular Matrix” Error?

The reason to get the error lies because we are doing those operations, which is not computationally possible. In the above case, the reason for the error is we want to inverse the matrix whose determinant is zero. Let’s see that.

Why do I get "LinAlgError Singular Matrix" Error

And when we work on matrices, there are several constraints and rules that we need to follow. Inverting a singular matrix is one of them. Inverting a singular matrix is practically impossible, and hence while applying the inverse function.

Solution to “LinAlgError Singular Matrix” Error

Now, the only solution to these errors is that you should avoid being in such scenarios. You should check the singularity of any matrix before applying any inverse operations on them. Moreover, it would be best never to forget the constraints on matrices while performing any operations on them.

This solution works in several scenarios where we get LinAlgError Singular Matrix-like building machine learning algorithms such as Logistic regression or deep learning model.

Solving ‘Remote End Closed Connection’ in Python!

Now, more often, when we work on some ML or DL project, we use more than one library simultaneously. Pandas are one of the significant tools in them. While performing some operations on matrix data, we might get LinAlgError Singular Matrix. Now, the reason for the error is the same as above, and we need to apply the same solution there. We choose to work on those data, which lets us avoid getting matrix data.

FAQs

Q1) Does Logit endog requires the y variable to be 0?

The endog y variable needs to be zero, one. However, in other cases, it is possible that the Hessian is not positive definite when we evaluate it far away from the optimum, for example, at bad starting values. Switching to an optimizer that does not use the Hessian often succeeds in those cases. For example, scipy’s ‘bfgs’ is a good optimizer that works in many cases.

Conclusion

Today, in this article, we learned about LinAlgError. We now understand the meaning of error and inspect the scenarios in which the error may occur.

I hope this article has helped you. Thank You.

Trending Right Now

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

What does the error Numpy error: Matrix is singular mean specifically (when using the linalg.solve function)? I have looked on Google but couldn’t find anything that made it clear when this error occurs.

strpeter's user avatar

strpeter

2,5023 gold badges26 silver badges48 bronze badges

asked Dec 10, 2012 at 5:47

KaliMa's user avatar

1

A singular matrix is one that is not invertible. This means that the system of equations you are trying to solve does not have a unique solution; linalg.solve can’t handle this.

You may find that linalg.lstsq provides a usable solution.

answered Dec 10, 2012 at 6:09

Michael J. Barber's user avatar

6

This function inverts singular matrices as well using numpy.linalg.lstsq:

def inv(m):
    a, b = m.shape
    if a != b:
        raise ValueError("Only square matrices are invertible.")

    i = np.eye(a, a)
    return np.linalg.lstsq(m, i)[0]

answered May 17, 2017 at 14:02

Procope's user avatar

ProcopeProcope

911 silver badge7 bronze badges

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться в Python:

numpy.linalg.LinAlgError: Singular matrix

Эта ошибка возникает, когда вы пытаетесь инвертировать сингулярную матрицу, которая по определению является матрицей с нулевым определителем и не может быть инвертирована.

В этом руководстве рассказывается, как устранить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, мы создаем следующую матрицу с помощью NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Теперь предположим, что мы пытаемся использовать функцию inv() из NumPy для вычисления обратной матрицы:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

Мы получаем ошибку, потому что созданная нами матрица не имеет обратной матрицы.

Примечание.Ознакомьтесь с этой страницей Wolfram MathWorld, на которой показаны 10 различных примеров матриц, не имеющих обратной матрицы.

По определению матрица сингулярна и не может быть обращена, если ее определитель равен нулю.

Вы можете использовать функцию det() из NumPy для вычисления определителя данной матрицы, прежде чем пытаться ее инвертировать:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

Определитель нашей матрицы равен нулю, что объясняет, почему мы сталкиваемся с ошибкой.

Как исправить ошибку

Единственный способ обойти эту ошибку — просто создать невырожденную матрицу.

Например, предположим, что мы используем функцию inv() для инвертирования следующей матрицы:

import numpy as np
from numpy. linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308 0.26923077]
 [ 0.15384615 -0.03846154]]

Мы не получаем никакой ошибки при инвертировании матрицы, потому что матрица не является единственной.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить: объект numpy.float64 не вызывается
Как исправить: объект ‘numpy.ndarray’ не вызывается
Как исправить: объект numpy.float64 не может быть интерпретирован как целое число

Python programming language provides us with various libraries to deal with several numeric, vectorized data and perform operations. Using them prevents us from doing computationally expensive tasks and makes our work easier. One such library is Numpy. It is used to perform mathematical operations on array and matrices. Some of them are cross-multiplication, dot-product, inverse e.t.c. While operating these matrices sometimes, we get errors like LinAlgError Singular Matrix. This article will try to understand the error and find suitable solutions for it.

So, LinAlgError is raised by linear algebra class (named linalg) when some linear algebra function prevents the correct execution of other program parts. The singular matrix is the sub-error raised when we perform incorrect operations on the singular matrix.

What is LinAlgError Singular Matrix Error?

LinAlgError Singular Matrix Error

So, in the above image, you can see that the interpreter threw a LinAlgError: Singular matrix. It means that the error occurred because of some linear algebra operation that is computationally incorrect. Talking more descriptively, we can say that some operations on a singular matrix are because of some operations. The matrix may not support those operations.

Why do I get “LinAlgError Singular Matrix” Error?

The reason to get the error lies because we are doing those operations, which is not computationally possible. In the above case, the reason for the error is we want to inverse the matrix whose determinant is zero. Let’s see that.

Why do I get "LinAlgError Singular Matrix" Error

And when we work on matrices, there are several constraints and rules that we need to follow. Inverting a singular matrix is one of them. Inverting a singular matrix is practically impossible, and hence while applying the inverse function.

Solution to “LinAlgError Singular Matrix” Error

Now, the only solution to these errors is that you should avoid being in such scenarios. You should check the singularity of any matrix before applying any inverse operations on them. Moreover, it would be best never to forget the constraints on matrices while performing any operations on them.

This solution works in several scenarios where we get LinAlgError Singular Matrix-like building machine learning algorithms such as Logistic regression or deep learning model.

Mastering Python Translate: A Beginner’s Guide

Now, more often, when we work on some ML or DL project, we use more than one library simultaneously. Pandas are one of the significant tools in them. While performing some operations on matrix data, we might get LinAlgError Singular Matrix. Now, the reason for the error is the same as above, and we need to apply the same solution there. We choose to work on those data, which lets us avoid getting matrix data.

FAQs

Q1) Does Logit endog requires the y variable to be 0?

The endog y variable needs to be zero, one. However, in other cases, it is possible that the Hessian is not positive definite when we evaluate it far away from the optimum, for example, at bad starting values. Switching to an optimizer that does not use the Hessian often succeeds in those cases. For example, scipy’s ‘bfgs’ is a good optimizer that works in many cases.

Conclusion

Today, in this article, we learned about LinAlgError. We now understand the meaning of error and inspect the scenarios in which the error may occur.

I hope this article has helped you. Thank You.

Trending Right Now

  • [Fixed] SSL module in Python is Not Available

    [Fixed] SSL module in Python is Not Available

    May 30, 2023

  • Mastering Python Translate: A Beginner’s Guide

    Mastering Python Translate: A Beginner’s Guide

    by Namrata GulatiMay 30, 2023

  • Efficiently Organize Your Data with Python Trie

    Efficiently Organize Your Data with Python Trie

    by Namrata GulatiMay 2, 2023

  • [Fixed] modulenotfounderror: no module named ‘_bz2

    [Fixed] modulenotfounderror: no module named ‘_bz2

    by Namrata GulatiMay 2, 2023


One error you may encounter in Python is:

numpy.linalg.LinAlgError: Singular matrix

This error occurs when you attempt to invert a singular matrix, which by definition is a matrix that has a determinant of zero and cannot be inverted.

This tutorial shares how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following matrix using NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Now suppose we attempt to use the inv() function from NumPy to calculate the inverse of the matrix:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

We receive an error because the matrix that we created does not have an inverse matrix.

Note: Check out this page from Wolfram MathWorld that shows 10 different examples of matrices that have no inverse matrix.

By definition, a matrix is singular and cannot be inverted if it has a determinant of zero.

You can use the det() function from NumPy to calculate the determinant of a given matrix before you attempt to invert it:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

The determinant of our matrix is zero, which explains why we run into an error.

How to Fix the Error

The only way to get around this error is to simply create a matrix that is not singular.

For example, suppose we use the inv() function to invert the following matrix:

import numpy as np
from numpy.linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308  0.26923077]
 [ 0.15384615 -0.03846154]]

We don’t receive any error when inverting the matrix because the matrix is not singular.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix: ‘numpy.float64’ object is not callable
How to Fix: ‘numpy.ndarray’ object is not callable
How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer

Hi, this is a (simplified) case I encountered while working on seaborn.pairplot.

data: data.1000.txt

singular.py:

import pandas
import seaborn
data = pandas.read_table("data.1000.txt", index_col="cell")
seaborn.pairplot(data.drop(columns="cluster").iloc[:,0:6], hue="batch")

commands:

~/w/experiments $ python3 --version
Python 3.6.6
~/w/experiments $ pip3 show seaborn
Name: seaborn
Version: 0.9.0
Summary: seaborn: statistical data visualization
Home-page: https://seaborn.pydata.org
Author: Michael Waskom
Author-email: mwaskom@nyu.edu
License: BSD (3-clause)
Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
Requires: numpy, scipy, pandas, matplotlib
Required-by:
~/w/experiments $ python3 singular.py
Traceback (most recent call last):
  File "singular.py", line 4, in <module>
    seaborn.pairplot(data.drop(columns="cluster").iloc[:,0:6], hue="batch")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/axisgrid.py", line 2111, in pairplot
    grid.map_diag(kdeplot, **diag_kws)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/axisgrid.py", line 1399, in map_diag
    func(data_k, label=label_k, color=color, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/distributions.py", line 691, in kdeplot
    cumulative=cumulative, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/distributions.py", line 294, in _univariate_kdeplot
    x, y = _scipy_univariate_kde(data, bw, gridsize, cut, clip)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/distributions.py", line 366, in _scipy_univariate_kde
    kde = stats.gaussian_kde(data, bw_method=bw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/stats/kde.py", line 172, in __init__
    self.set_bandwidth(bw_method=bw_method)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/stats/kde.py", line 499, in set_bandwidth
    self._compute_covariance()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/stats/kde.py", line 510, in _compute_covariance
    self._data_inv_cov = linalg.inv(self._data_covariance)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/linalg/basic.py", line 975, in inv
    raise LinAlgError("singular matrix")
numpy.linalg.linalg.LinAlgError: singular matrix

0 / 0 / 1

Регистрация: 03.10.2020

Сообщений: 85

1

Проблемы с генератором пилообразного напряжения

01.12.2022, 12:03. Показов 556. Ответов 6


Студворк — интернет-сервис помощи студентам

Я в Microcap 12 создал схему генератора пилообразного напряжения.

Проблемы с генератором пилообразного напряжения

Я ожидал увидеть на выходе повторителя пилообразный сигнал.

Проблемы с генератором пилообразного напряжения

Но по итогу получаю ошибку о том, что сигнала нет. С чем это может быть связано?



0



3030 / 2213 / 510

Регистрация: 11.09.2009

Сообщений: 8,193

01.12.2022, 12:19

2

Цитата
Сообщение от Sergei200
Посмотреть сообщение

получаю ошибку о том, что сигнала нет

Покажите картинку ошибки.



0



0 / 0 / 1

Регистрация: 03.10.2020

Сообщений: 85

01.12.2022, 14:06

 [ТС]

3

i8085, Error: Matrix is singular.
This message occurs when a circuit produces a singular matrix.
The most common causes of singularities are structural and are caused by voltage loops and missing paths to ground.
These are checked for separately before the analysis is run, so if you get this message, the problem lies in the nature of the circuit.
Singularities can occur because of extreme nonlinearities and strong negative feedback in the circuit.
Это сообщение появляется, когда схема генерирует сингулярную матрицу.
Наиболее распространенные причины особенностей являются структурными и вызваны контурами напряжения и отсутствующими путями заземления.
Они проверяются отдельно перед запуском анализа, поэтому, если вы получаете это сообщение, проблема заключается в природе схемы.
Особенности могут возникать из-за экстремальных нелинейностей и сильной отрицательной обратной связи в цепи.



0



356 / 298 / 98

Регистрация: 27.05.2017

Сообщений: 1,639

01.12.2022, 16:19

4

Лучший ответ Сообщение было отмечено Sergei200 как решение

Решение

Можно в Протеусе, там всё нормально. Или Microcap непременное условие?

Миниатюры

Проблемы с генератором пилообразного напряжения
 



1



3030 / 2213 / 510

Регистрация: 11.09.2009

Сообщений: 8,193

01.12.2022, 16:23

5

Лучший ответ Сообщение было отмечено Sergei200 как решение

Решение

Sergei200, ааа, то есть ошибка вываливается до симуляции…
Попробуйте зашунтировать конденсаторы резисторами 100 МОм.



1



0 / 0 / 1

Регистрация: 03.10.2020

Сообщений: 85

01.12.2022, 17:17

 [ТС]

6

Лучший ответ Сообщение было отмечено i8085 как решение

Решение

i8085, Я понял из-за чего не получалось У меня один из элементов, как бы был подключен к земле, но программа что то решила, что не подключен.



0



3030 / 2213 / 510

Регистрация: 11.09.2009

Сообщений: 8,193

01.12.2022, 19:52

7

Sergei200, Для тех, кто будет наступать на те же грабли, напишите, как так получилось.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

01.12.2022, 19:52

7

In python, the Base exception is the class from which all instances of exceptions are derived. Exceptions may be raised by built-in functions or the interpreter or both. User-defined programs can also raise exceptions . One such example of a built-in exception is the LinAlgError. The LinAlgError is raised by the linalg or the linear algebraic functions which mainly involve matrices.

It is a generic-python-exception- derived object raised by the linalg functions. This exception class is raised when a linear algebraic condition hinders the correct execution of a specific linalg function.

Understanding Singular Matrices and the ‘Singular Matrix Error’ in Python

This exception is mainly raised when a matrix is singular but an in-built function or user defined block of code tries to invert it. Hence, when the determinant of a matrix is zero and you try to invert it, python will raise this exception .

A singular matrix is often referred to as a degenerate matrix because it is invertible in nature. If the determinant of a matrix is non-zero, the matrix is non-singular in nature and can be inverted.

A matrix that is positive definite can be inverted.

How does the Error look like?

For example, let’s say you have matrix as follows:

Now, if you try to invert this matrix using the linalg.inv() function, it will raise a LinAlgError because the given matrix is singular in nature as it’s determinant,

import numpy as np
A=np.array([[1,2],[-2,-4]])
#using the inverse function to invert the singular matrix
b=np.linalg.inv(A)
print(b)

The above code raises the LinAlg Error.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    b=np.linalg.inv(A)
  File "<__array_function__ internals>", line 200, in inv
  File "/home/runner/BisqueFrightenedMap/venv/lib/python3.10/site-packages/numpy/linalg/linalg.py", line 538, in inv
    ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
  File "/home/runner/BisqueFrightenedMap/venv/lib/python3.10/site-packages/numpy/linalg/linalg.py", line 89, in _raise_linalgerror_singular
    raise LinAlgError("Singular matrix")
numpy.linalg.LinAlgError: Singular matrix

LinAlgError

The raised LinAlgError

How to solve the LinAlg Error

The only way to solve or avoid this exception is by checking whether the determinant of an argument matrix is zero or not. Since degenerate matrices have limited functionality for scientific computations, it is always better to check the determinant of a matrix. This can be done using the numpy.linalg.det() function. Calculate the determinant of a matrix in the following way:

#importing required numpy module
import numpy as np
A=np.array([[1,2],[-2,-4]])
print("the matrix is=",A)
#computing the determinant of a matrix
b=np.linalg.det(A)
#check if the matrix is degenerate
if (b==0):
  print("The matrix is singular hence cannot be inverted")
else:
  print("The inverse of the matrix is=")
  c=np.linalg.inv(A)
  print(c)

The above code will give us the following output:

the matrix is= [[ 1  2]
 [-2 -4]]
The matrix is singular hence cannot be inverted

Avoiding The Exception

Avoiding The Exception.

List of functions that raise a LinAlg Error

Almost all of the linear algebraic functions in the numpy library raise this error when a degenerate matrix is passed as the argument. Some of them are:

  • numpy.linalg.cholesky(a), the function that computes the Cholesky decomposition of a matrix, raises this error when the decomposition fails, that is, when a, the given matrix is not positive definite.
  • linalg.qr(a) which computes the QR factorization of a matrix raises the LinAlgError when the factorization fails.
  • linalg.inv(a) computes the inverse of an N-dimensional array. The LinAlgError is raised when the given matrix is not singular or square.
  • numpy.linalg.lstsq computes the least square solution of a linear equation system, raising the error when the coefficient matrix is invertible.

To see the full list of functions that might raise the LinalgError, visit the official numpy linear algebra documentation.

Conclusion

This article outlines the causes and possible explanations for the LinAlgError which is a generic python exception-derived object raised by the numpy Linear algebraic functions or simply the LinAlg functions. We have provided a possible work for this exception which could help you in suppressing the Linalg Error in the future.

The numpy.linalg.linalgerror: singular matrix error occurs in Python when you attempt to invert a singular matrix whose determinant is zero that cannot be inverted.

To fix the LinAlgError: Singular matrix error, create a matrix that is not singular, and the determinant is not 0.0.

Python code that generates numpy.linalg.linalgerror: singular matrix

import numpy as np

#create 2x2 matrix
main_matrix = np.array([[21., 21.], [21., 21.]]) 

# attempt to print the inverse of matrix
print(np.linalg.inv(main_matrix))

Output

numpy.linalg.linalgerror - singular matrix

You can see that we got the “LinAlgError: Singular matrix” error because the main_matrix is not invertible. It has the same value in all entries, making it a singular matrix with zero determinant.

The numpy.linalg.LinAlgError is an exception class for general purposes, derived from Python’s exception.

When a Linear Algebra-related condition prevents continued accurate execution of the function, this exception class is raised programmatically in linalg functions.

A matrix is invertible only if its determinant is non-zero.

If the determinant is zero, the matrix is said to be singular and has no inverse.

You can use the np.linalg.det() function from NumPy to calculate the determinant of a given matrix before you try to invert it.

import numpy as np 

# create 2x2 matrix 
main_matrix = np.array([[21., 21.], [21., 21.]]) 

# Printing the determinant
print(np.linalg.det(main_matrix))

Output

You can see that the determinant of the matrix is zero, which explains why we get into the error.

Code that fixes the error

import numpy as np 

# create 2x2 matrix 
main_matrix = np.array([[21., 19.], [19., 21.]]) 

# Printing the inverse of matrix
print(np.linalg.inv(main_matrix))

Output

[[ 0.2625 -0.2375]
 [-0.2375  0.2625]]

You can see that the code worked without errors and will print the inverse of the main_matrix.

In this case, the main_matrix is a 2×2 matrix with a non-zero determinant, which is invertible.

The np.linalg.inv() function from the NumPy library is used to find the inverse of the main_matrix.

I hope this solution will resolve your error.

Приложение 4. Сообщения об ошибках

71

Приведенная далее информация об ошибках вычислений выполнена по следующей схеме: текст сообщения об ошибке (перевод сообщения) — вероятная причина ошибки — возможные пути устранения ошибки.

Сообщения об ошибках в численных вычислениях

A «Find» or «Minerr» must be preceded by a matching «Given» (Функциям find или minerr должно предшествовать ключевое слово given). Эта ошибка выделяет функцию find или minerr при их несогласованности с given. Каждый вычислительный блок, который заканчивается функцией find или minerr, должен начинаться с ключевого слова given.

All evaluations resulted in either an error or a complex result (Вычисления приводят к ошибке или к комплексному результату). Mathcad не может начертить некоторые точки, потому что не существует действительных значений для их нанесения на график. Это сообщение может появиться, если имеется ошибка или все значения — комплексные.

Arguments in function definitions must be names (Аргументы в определениях функции должны быть именами). Выделенное определение функции содержит неправильный перечень аргументов. В списке аргументов должны быть правильно поименованы переменные или список имен необходимо отделить запятыми.

All the elements in the vector cannot be the same (Все элементы вектора не могут быть одинаковыми). Если используется встроенная функция, возможно, неправильно указаны ее имя или параметры. Проверьте правильность ввода встроенной функции, установив курсор на имени функции и нажав клавишу F1.

At least one limit must be infinity (По крайней мере один предел должен быть бесконечным). Если для интегрирования выбран алгоритм бесконечного предела, то по крайней мере один из пределов интеграла должен быть бесконечным.

Символ бесконечности вводится нажатием комбинации клавиш Ctrl+Shift+z. Для изменения алгоритма, использующего бесконечный предел, или для вычисления какого-либо другого интеграла щелкните на интеграле правой кнопкой мыши и измените алгоритм с помощью контекстного меню.

Can only evaluate an nth order derivative when n=0, 1..5 (Можно вычислить n

порядок производной, только когда n = 0, 1, 2, , 5). Порядок производной должен быть целым числом от 0 до 5. Если нужно посчитать производную более высокого порядка, сделайте это с помощью символьного дифференцирования.

Can only plot positive values when log axes are used (Только положительные величины могут быть на графике, если используются логарифмические координаты). Двухмерный график в декартовых или полярных координатах строится в логарифмических координатах, в которых не может быть величин отрицательных или равных нулю.

Can’t converge to a solution. Encountered too many integrator steps (Невозможно найти решение. Сделано слишком много шагов интегрирования). Алгоритм решения дифференциального уравнения не позволяет найти решение этого уравнения. Попробуйте изменить начальные или граничные условия. Возможно, решения просто не существует.

Can’t converge to a solution. The integrand may have a singularity or the integral may not be finite (Невозможно найти решение. Подынтегральное выражение может иметь точку сингулярности или интеграл может быть бесконечным). Вычисление интегралов, производных, функций root, find, minerr осуществляется итерационными методами. Вы увидите это сообщение, если после большого числа итераций не получен ответ с требуемой точностью.

Попробуйте изменить значение постоянной TOL. При работе с функциями root, find, minerr попробуйте задавать различные значения начальных приближений.

Can’t define the same variable more than once in the same expression (Невозможно определить ту же самую переменную более одного раза в одном и том же выражении). Вы пытаетесь вычислить одну и ту же переменную дважды в одном выражении. Пример подобной ошибки: если вы создаете вектор с именем a:= и используете это же имя справа, то получите это сообщение.

Can’t determine what units the result of this operation should have (Невозможно определить, в каких единицах должен быть представлен результат операции). Вы возвели выражение, содержащее единицы измерения, в степень, являющуюся переменной или вектором. В итоге невозможно определить размерность результата. Если выражение имеет размерность, то его можно возводить только в действительную фиксированную степень.

Can’t evaluate this expression. It may have resulted in an overflow or an infinite loop

(Невозможно вычислить это выражение. Это может быть результатом переполнения или бесконечным числом циклов). Это выражение может содержать слишком много вложенных функций или функция может быть константой в бесконечных циклах.

Проверьте несколько итераций цикла.

Can’t evaluate this expression because it’s either too complicated or it’s defined in terms of itself (Невозможно вычислить это выражение, потому что оно или слишком сложное,

или определяет само себя). Эта ошибка возникает, если функция определена в 72 терминах самой себя, что ведет к появлению рекурсивной функции, где условие

окончания процесса не определено. Например, f(x) := f(x)+5 ведет к переполнению стека. Необходимо изменить имя функции.

Как правило, имена функций слева и справа должны быть разными, если, конечно, это не рекурсивная функция.

Can’t evaluate this function when its argument is zero (Невозможно вычислить эту функцию, если ее аргумент равен нулю). Функция неопределенна, если аргумент равен нулю. Такое сообщение появляется при вычислении логарифма от нуля. Can’t divide by zero (Деление на ноль невозможно). Где-либо в программе или внутри численного метода возникло деление на ноль. Найдите место деления на ноль и устраните его. Попробуйте поменять параметры численного метода, константы точности или сам численный алгоритм.

Can’t find a solution. Encountered too many iterations (Невозможно найти решение.

Слишком много итераций). Это сообщение появляется при использовании функции polyroot, если степень полинома слишком велика. Попробуйте найти корни полинома символьным методом.

Can’t find a solution to this system of equations (Невозможно найти решение системы уравнений). Попробуйте изменить начальные приближения.

Что делать, если функция find не может найти решение, описано в главе 3.

Can’t find the data file you’re trying to use (Невозможно найти файл, который вы пытаетесь использовать). Удостоверьтесь, что такой файл существует в указанном месте.

Can’t have anything with units or dimensions here (Здесь не должно быть единиц измерений или размерностей). Это выражение использует единицы измерений гделибо, где они не разрешены.

Единицы измерений не разрешены:

варгументах большинства функций;

вэкспонентах;

вверхних и нижних индексах.

Для того чтобы использовать выражения с единицами измерений, вначале переведите это выражение в UnitsOf(выражение).

Can’t have more than one array in a contour plot (Не может быть более одного массива в контурном графике). Вы вводите более одного массива в место ввода контурного или поверхностного графика. Разрешается иметь только один массив в данном месте ввода, так как на контурном графике может быть изображена только одна поверхность.

Can’t plot this many points (Невозможно начертить график с таким большим количеством точек). Попытка построения графика с числом точек, превосходящим возможное. Попробуйте сделать число точек меньшим, чем 150 000.

Can’t perform this operation on the entire array at once. Try using «vectorize» to perform it element by element (Невозможно выполнить эту операцию во всем массиве сразу. Попытайтесь использовать векторизацию, чтобы преобразовать элемент за элементом). Это сообщение можно увидеть, например, при попытке разделить один вектор на другой.

Для того чтобы применить функцию или оператор к каждому элементу вектора или матрицы, используйте оператор векторизации.

Can’t raise an expression having units to a complex power (Нельзя возводить в комплексную степень выражение, имеющее единицы измерения). Выражение с единицами измерения можно возводить только в действительную степень. Для того, чтобы возвести в комплексную степень выражение с единицами измерения, вначале переведите это выражение в UnitsOf(выражение) — единицы измерения будут отменены.

Can’t solve a system having this many equations (Невозможно решить систему,

имеющую так много уравнений). Mathcad может решать системы уравнений, содержащие не больше 200 нелинейных уравнений и не больше 500 линейных.

Can’t understand something in this data file. If this file came from a spreadsheet, make sure you saved it as ASCII text only (Невозможно что-либо понять в этом файле данных. Если этот файл взят из откуда-либо из готовых материалов, убедитесь, что он сохранен в формате ASCII). При считывании файла функцией READPRN файл должен быть записан в формате ASCII.

Все строки в файле должны иметь одинаковое число величин. Строки, не содержащие численных величин, игнорируются. Если файл имеет требуемый формат, а вы видите это сообщение об ошибке, удалите из файла любой текст.

Can’t understand the name of this function. If you’re trying to multiply, use «*»

(Невозможно понять имя этой функции. Если вам нужно умножить, используйте знак умножения). Такое сообщение появляется, если выражение, не являющееся функцией, используется как функция или имя функции записано неверно.

Can’t understand the way this range variable is defined (Невозможно понять определение дискретной (ранжированной) переменной). Неверное определение дискретной переменной.

Дискретная переменная может быть определена двумя способами:

var := n1

..n2 ;

var := n1

, n2 ..n3 .

73

Can’t understand this number (Невозможно понять это число). Это выражение содержит символ или десятичную точку там, где это непозволительно. Например, вы увидите этой сообщение об ошибке, если случайно запишете число как .452.

Can’t use a range variable in a solve block (Невозможно использовать дискретную переменную в вычислительном блоке). Эта сообщение об ошибке появляется, если использовать дискретную переменную в неподходящем месте, например, в вычислительном блоке.

Исключите дискретную переменную из вычислительного блока. Попробуйте создать функцию, включающую в себя вычислительный блок.

Cannot evaluate this accurately at one or more of the values you specified (Невозможно точно вычислить выражение в одной или нескольких точках). Эта ошибка указывает, что вы пытаетесь вычислить функцию для аргумента, находящегося за пределами области определения функции.

Cannot perform this operation on a string (Нельзя выполнить эту операцию над строкой). Нельзя выполнить математические операции со строковой переменной. Could not find a solution (Невозможно найти решение). Численный метод расходится (не может найти решения). Возможно, решения не существует. Подробнее об этом написано в главе 3.

Could not find a solution because the root finder failed (Невозможно найти решение.

Сбой при нахождении корней). При решении дифференциального уравнения с граничными условиями функция sbval не может вычислить недостающие начальные условия. Попробуйте изменить начальные приближения.

Cross product is defined only for vectors having exactly three elements (Векторное произведение определяется только для векторов, имеющих ровно три элемента).

Degree of the polynomial must be between 1 and 99 (Степень полинома должна быть от

1 до 99). Вектор коэффициентов полинома, используемый функцией polyroot, должен содержать от 2 до 99 элементов.

Encountered a floating point error (В заданной точке функция не может иметь такого значения).

End of File (Конец файла). Вы пытаетесь функцией READ прочитать больше данных, чем есть в файле.

End points cannot be the same (Конечная и начальная точки не могут быть одинаковыми). При решении дифференциальных уравнений конечные точки интервала интегрирования должны быть разными.

Found a number with a magnitude greater than 10^307 while trying to evaluate this expression (Найдено число, превышающее 10307). Попробуйте поменять параметры численного алгоритма или сам алгоритм.

Found a singularity while evaluating this expression. You may be dividing by zero

(Обнаружена сингулярность при вычислении этого выражения. Возможно деление на ноль). Проверьте численные значения величин в этом выражении.

Illegal context. Press F1 for Help (Недопустимый контекст. Нажмите клавишу F1, чтобы получить помощь). Трудно диагностируемая ошибка. Часто вызывается синтаксическими ошибками при наборе выражений.

При использовании в правой части выражения переменных с индексами или дискретных переменных все индексы и все дискретные переменные обязательно должны появиться и в левой части выражения в качестве индексов или параметров функции.

Illegal dimensions (Недопустимые размеры массива). Массив не имеет столько строк и столбцов, сколько требуется.

Введите имя массива и нажмите клавишу =, чтобы проверить истинные размеры массива.

Invalid expansion point (Невозможно разложить выражение в ряд в окрестности указанной точки). Проверьте правильность использования ключевого слова series при символьном вычислении выражения.

Invalid matrix dimension. The number of rows is less than the number of columns

(Неправильный размер матрицы. Число строк меньше, чем число столбцов). Функция svd требует, чтобы число строк было больше числа столбцов или равно ему.

Live symbolics not available (Символьные вычисления невыполнимы). Это сообщение появляется при использовании символьного знака равенства, если в данной версии Mathcad символьные вычисления отсутствуют.

Loess cannot extrapolate (Функция loess не может экстраполировать выражение). Точки для интерполяции выражения должны лежать между минимальным и максимальным значениями заданных точек.

Matrix is singular. Cannot compute its inverse (Матрица сингулярная. Невозможно вычислить обратную матрицу). Матрица вырожденная или почти вырожденная. Ее определитель равен нулю или число обусловленности очень велико.

Matrix must be positive definite (Матрица должна быть положительно определенной). Это сообщение появляется, когда матричный аргумент функции не является

положительно определенным. Матрица является положительно определенной, если

ее собственные числа действительные и положительные.

Must be 1 complex matrix or 2 real matrices (Должна быть одна матрица комплексных

74

чисел или две матрицы действительных чисел). Это условие необходимо при

построении графика векторного поля.

Must be a vector with real elements (Должен быть вектор действительных чисел).

Вектор не должен иметь мнимых чисел и должен быть столбцом, а не строкой.

Must be between two lock regions (Курсор должен быть между границами запираемой

зоны). При создании закрытой области — команда Format

Area

Lock

(Формат

Зона

Запереть) — необходимо вначале щелкнуть мышью между

границами запираемой зоны.

Must be less than the number of data points (Аргумент должен быть меньше, чем число

точек в массиве данных). Для дополнительной информации установите курсор на

названии встроенной функции и нажмите клавишу F1.

Must be a real scalar (Должно быть действительным числом).

Must have more than four rows (Матрица должна иметь больше четырех рядов).

Must have 1 or 2 columns (Матрица должна иметь один или два столбца). Первый

матричный аргумент в функциях кубической сплайн-интерполяции должен иметь

один столбец для одномерной сплайн-интерполяции и два столбца — для

двухмерной.

Must have three vectors or one matrix (Должно быть три вектора или одна матрица).

При построении графика поверхности в поле ввода надо вписать или три вектора,

разделенных запятыми, или одну матрицу.

No bitmaps were found in the worksheet (В документе нет графических объектов). Это

сообщение появляется при выполнении команды Format

Color

Optimize Palette.

(Формат

Цвет

Оптимизировать палитру).

Not enough memory for this operation (Для этой операции недостаточно памяти).

Only positive values are allowed here (Здесь можно использовать только положительные величины).

ORIGIN should be an integer whose magnitude is less than 16 million (ORIGIN должно быть целым числом, меньшим 16 млн).

(Rows – 1) must be power of 2 (Матрица должна иметь 2n рядов).

Something is wrong with the solve block used to define this function. It may need a guess value (Что-то неверно в блоке решения. Возможно, необходимо начальное приближение). Такое сообщение появляется при использовании блока решения внутри функции пользователя. Попробуйте оценить непосредственно сам блок решения вне функции пользователя. Вы получите другое более подробное сообщение об ошибке.

String contains the wrong number of characters or the wrong kind of characters (Строка содержит неверное число символов или неверный вид символов). При использовании смешанных программ необходим ввод символов в строке аргументов: I — для целых чисел, B — для бинарных чисел, С — для любого вещественного числа.

The elements in this vector must be in increasing order (Элементы этого вектора должны быть расположены в порядке возрастания). Такое требование предъявляется к вектору аргументов при работе с массивами данных, например, при интерполяции или построении гистограмм.

The expression to the left of the equal sign cannot be defined (Выражение слева от знака равенства не может быть определено). Возможна синтаксическая ошибка. Слева от оператора присваивания могут находиться имена переменных, векторов, матриц и функций (с аргументами в скобках).

The format of this vector is invalid. Press F1 for help (Неверный размер вектора.

Нажмите клавишу F1 для вызова помощи). Некоторые функции требуют в качестве аргумента вектор, созданный другой функцией. Этот вектор имеет специальный формат, создаваемый другой функцией, например cspline, regress и др.

The function values on the two bracket end points must be of opposite signs (Величины функции в двух крайних точках интервала должны быть разного знака). При задании интервала поиска корней функцией root величины функции в двух крайних точках интервала должны быть разного знака. Выбирайте границы интервала поиска корней после построения графика функции.

The number of rows must be a power of 2 (Число элементов вектора должно быть равно 2n). Ошибка возникает при неверном числе данных для волнового преобразования функцией wave.

The number of rows or columns do not match (Число строк и столбцов в этих матрицах не согласовано). Подобное сообщение об ошибке часто появляется при неправильном перемножении матриц. Нажмите клавиши Shift+F1 и щелкните мышью на имени функции, чтобы узнать необходимые размеры матриц.

The unit placeholder can only have real, non-zero scalars put into it (В место ввода размерности при выводе результатов вычислений можно вводить, кроме размерностей, только действительные, не равные нулю скалярные величины).

The units in this expression do not match (Размерности в этом выражении не согласованы). Несогласованные вычисления с размерными и безразмерными величинами. При вычислениях без учета размерностей, видимо, осталась не заданной

какая-либо величина, обозначенная буквами m, s, N и т. д., которые по умолчанию встроены в Mathcad как стандартные размерности длины, времени и силы.

There is an extra comma in this expression (В этом выражении есть лишняя запятая). 75

Проверьте синтаксис. Видимо, запятая использована вместо точки.

There must be more data points than parameters (В массиве данных должно быть больше точек, чем параметров функции). Такое требование предъявляют, например,

функции regress и genfit.

There must be more than three data points (Эта функция требует вектор, содержащий по крайней мере четыре элемента).

This array must have more than one row or column (Этот массив должен иметь больше,

чем одну строку или столбец). Например, при построении графиков поверхности требуется матрица значений. Некоторые функции требуют матричных аргументов.

This expression has a «(» without a matching «)». (В выражении не хватает скобок).

Проверьте выражение.

This expression is incomplete. You must fill in the placeholders (Выражение неполное.

Вы должны заполнить места ввода).

This expression is incomplete. You must provide an operator (Выражение неполное. Вы должны ввести оператор).

This expression is too complicated. Try defining it in smaller pieces (Выражение слишком сложное. Постарайтесь определить его по частям).

This file could not be opened. Make sure it exists (Этот файл не может быть открыт.

Убедитесь, что он существует). При считывании внешнего файла функцией READPRN возможно, что файл имеет статус «только для чтения». Если считываемый файл не находится в том же каталоге, что и файл, используемый Mathcad, необходимо указать полный путь к нему.

This function has too many arguments (Функция имеет слишком много аргументов). Для встроенных функций щелкните мышью на имени функции и нажмите клавишу F1. Проверьте правильность использования функции. Для функции пользователя проверьте определение функции.

This function is undefined at one or more of the points you specified (Функция не определена в одной или нескольких точках). Вы используете оператор или функцию для неприемлемых значений аргумента, например, lg(0) или –3! (факториал отрицательного числа не определен).

This image format is not supported (Этот формат изображения не поддерживается

Mathcad).

This integer is too large (Величина слишком большая для работы с ней). This integer is too small (Величина слишком мала для работы с ней).

This is invalid. If you are using conditional statements in a Mathcad program, make sure all cases are accounted for (Это неверно. Если вы используете условие в Mathcadпрограмме, убедитесь, что все возможные случаи учтены). В условный оператор программирования добавьте еще одно место ввода и впишите еще одно значение с ключевым словом Otherwise (иначе).

This is not a valid interval (Неправильно указан интервал). Начальное значение интервала должно быть меньше конечного.

This is not allowed inside a solve block. For example, definitions are not allowed in a solve block (Это не разрешено внутри вычислительного блока. Например, определения не могут находиться внутри вычислительного блока). Внутри вычислительного блока могут находиться только решаемые уравнения и ограничения к ним.

This list contains too many items (Список содержит слишком много имен). Вы ввели в список слишком много имен, разделенных запятыми. Чаще всего это случается с графиками.

This matrix must be square. It should have the same number of rows as columns (Матрица должна быть квадратной. Число строк должно быть равно числу столбцов).

This must be an integer. The expression you used appears to have a fractional part (Здесь должно быть целое число. Похоже, что выражение содержит дробную часть). Проверьте верхние и нижние индексы. Они должны быть целыми числами. Некоторые функции, такие как identity и submatrix, требуют целочисленных аргументов.

This must be the name of a function or variable (Здесь должно быть имя функции или переменной).

This must be the name of a mapping function (Здесь должно быть имя функции преобразования координат). Такой аргумент требуется функциям CreateMech и CreateSpace.

This operation can only be performed on a function (Эту операцию можно производить только над функцией). Аргумент функции сам должен быть функцией.

This operation can only be performed on an array. It can’t be performed on a number (Эту операцию можно выполнить только над массивом, но не над числом). Например, если вы пишете имя с верхним индексом, то это должен быть вектор.

This operation can only be performed on a number or an array (Эту операцию можно выполнить только над числом или массивом).

This operation can only be performed on a string (Эту операцию можно выполнить только над строкой). Например, строковые функции требуют хотя бы один строковый аргумент.

Понравилась статья? Поделить с друзьями:
  • This is not pro 800 signature ошибка при обновлении
  • This is new car over there исправить ошибку
  • This is my bedroom исправь пунктуационные ошибки
  • This form is undefined ошибка
  • This folder is not empty ошибка