(Воспроизведено) Matlab вращает, переворачивает влево и вправо и переставляет матрицу
При использовании программного обеспечения Matlab для программирования вычислений вы часто сталкиваетесь с такими операциями, как поворот матрицы, поворот влево и вправо, поворот вверх и вниз и перестановка строк и столбцов элементов матрицы. Вот небольшой пример, в котором представлены функции rot90 (), fliplr (), flipud (), reshape () и другие функции.
Сначала введите следующий код, чтобы попасть в матрицу 3 × 3
% Создать матрицу 3 × 3 A
Результат бега показан на рисунке.
rot90 () функция вращения
Повернуть матрицу A против часовой стрелки, угол поворота 90 градусов
Результат показан на рисунке.

Повернуть матрицу A против часовой стрелки, угол поворота 180 градусов
Результат показан на рисунке.
Видно, что угол поворота матрицы составляет 2 × 90 градусов по вращению (90,2). По аналогии его можно повернуть на 3 × 90 градусов, 4 × 90 градусов и т. Д.

Поверните налево и направо, вверх и вниз
Функция fliplr () представляет собой матричную функцию переворота влево и вправо, конкретная операция
Выполните операцию переворота влево и вправо на матрице A
Результат показан на рисунке.

Функция flipud () — это функция переворота матрицы вверх и вниз, конкретная операция
Переверните матрицу A вверх и вниз
Результат показан на рисунке.

Переставьте строки и столбцы матрицы
Функция reshape () — это функция для переупорядочивания строк и столбцов матрицы. Следует отметить, что количество элементов в матрице не может быть изменено в процессе упорядочивания. В этом примере количество элементов равно 9, поэтому его можно изменить только на 9 × 1. Две формы 1 × 9.
Измените матрицу A с 3 × 3 на 9 × 1, то есть 9 строк и 1 столбец, результат показан на рисунке

Измените матрицу A с 3 × 3 на 1 × 9, то есть 1 строку и 9 столбцов, результат показан на рисунке
матлаб флип-матрица
Как перевернуть матрицу и получить такой результат в Matlab? Я не хочу, чтобы это было в отсортированном порядке. Спасибо.
задан 25 июн ’12, 20:06
Добро пожаловать в Stack Overflow! Что вы пробовали? — Matt Ball
Будет ли это всегда заканчиваться отсортированными строками? Если это так, вы можете использовать sort(A,2,’descend’). — ioums
Вы пытаетесь перевернуть всю строку? Упорядочить значения в строке от большего к меньшему? Это внешность как будто вы просто заказываете их, потому что вы игнорируете все 0 клетки. — gkiar
извините, я просто понимаю, что не хочу, чтобы он был в отсортированной строке. Я просто хочу перевернуть всю матрицу. пример матрицы = . [ 1 5 1 0 0 ; 6 2 3 1 0 ] будет иметь результирующую матрицу = . [ 1 5 1 0 0 ; 1 3 2 6 0 ] — jive
3 ответы
Изменение размера не требуется, если вы хотите перевернуть столбцы с 1 по 4, вы можете использовать следующее:
Это будет работать для любого произвольного списка столбцов
Как это работает?
Сначала выберите интересующие вас столбцы:
Отразите их по горизонтали с помощью
Сохраните отраженную матрицу обратно в подраздел исходной матрицы с помощью:
Это не сработает, так как есть строки только с тремя ненулевыми элементами. — Jonas
@ Джонас, хм .. Я не заметил, что в некоторых строках было 3 значения. — Slayton
Из ваших комментариев я думаю, что вы хотите следующее:
- Найдите последний ненулевой элемент в каждой строке, назовите его lastNZ
- Обратный порядок элементов 1:lastNZ в строке
Это должно сделать работу:
Хотя, если у вас никогда не было встроенных нулей в строках, решение ioums будет работать достаточно хорошо. — Sfstewman
Что ж, поскольку вы не хотите, чтобы строки заканчивались сортировкой, ответ Слейтона будет работать с небольшим изменением, чтобы учесть разное количество нулей. Что-то типа:
Если вам нужно однострочное решение (которое, вероятно, не будет быстрее, чем цикл for, и более запутанно для чтения), вы можете использовать
Я делаю предположение, что ваши матрицы не имеют нулей, которые являются частью переупорядочения (например, [ 1 5 1 0 0 ; 6 0 3 1 0 ] переходят в [ 1 5 1 0 0 ; 1 3 0 6 0 ]). Если это предположение неверно, мой код необходимо изменить.
Большое спасибо. Эта работа великолепна! Еще раз большое спасибо за ваше время. И нет, у меня не будет нуля между числами. я ставлю только ноль в конце, чтобы матрица была ровной по размерам. — джайв
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками matlab or задайте свой вопрос.
Какой самый быстрый способ развернуть матрицу в MATLAB?
Сейчас я использую цикл for, но это занимает много времени.
4 ответа
Вот вариант использования ind2sub :
Обратите внимание , что индексы перевернуты по сравнению с вашим примером.
Если вы не возражаете против другого порядка (согласно вашему редактированию), вы можете сделать это проще:
Помимо создания индексов строк / столбцов с помощью meshgrid , вы можете использовать все три выхода find следующим образом:
Ограниченное применение, потому что теряются нули . Противное, но верное решение (спасибо user664303):
Излишне говорить, что я бы порекомендовал одно из других решений. 🙂 В частности, ndgrid — наиболее естественное решение для получения строки col inds.
Я считаю ndgrid наиболее естественным решением, но вот интересный способ сделать это вручную с помощью нечетной пары kron и repmat :
Простая настройка для чтения, как это естественно в MATLAB:
(Кроме того, поскольку мой первый ответ был непристойно хакерским.)
Я также считаю, что kron — хороший инструмент для копирования каждый элемент за раз, а не весь массив за раз, как это делает repmat . Например:
Пройдя немного дальше, мы можем сгенерировать новую функцию под названием repel для репликации элементов массива, а не всего массива:
Operations on matrices
Matlab stands for ‘matrix laboratory’. Not surprisingly, matrices, vectors and multidimensional arrays are at the heart of the language. Here we describe how to create, access, modify and otherwise manipulate matrices — the bread and butter of the Matlab programmer.
Contents
Creating Matrices
There are a number of ways to create a matrix in Matlab. We begin by simply entering data directly. Entries on each row are separated by a space or comma and rows are separated by semicolons, (or newlines). We say that this matrix is of size 4-by-3 indicating that it has 4 rows and 3 columns. We, (and Matlab) always refer to rows first and columns second.
We can often exploit patterns in the entries to create matrices more succinctly.
We can also create an empty matrix.
Alternatively, there are several functions that will generate matrices for us.
The functions true() and false(), act just like ones() and zeros() but create logical arrays whose entries take only 1 byte each rather than 32.
The Size of a Matrix
We can determine the size of a matrix by using the size() command
and the number of elements by using the numel() command.
We refer to dimensions of size 1 as singleton dimensions. The length() command gives the number of elements in the first non-singleton dimension, and is frequently used when the input is a row or column vector; however, it can make code less readable as it fails to make the dimensionality of the input explicit.
We can also determine the size along a specific dimension with size().
Transposing a Matrix
A m-by-n matrix can be transposed into a n-by-m matrix by using the transpose operator ‘.
Sums and Means
You can use the sum() and mean() functions to sum up or take the average of entries along a certain dimension.
The [] argument to the min and max functions indicates that you will specify a dimension.
Concatenating Matrices
Matrices can be concatenated by enclosing them inside of square brackets and using either a space or semicolon to specify the dimension. Care must be taken that the matrices are of the right size or Matlab will return an error.
Basic Indexing
Individual entries can be extracted from a matrix by simply specifying the indices inside round brackets. We can also extract several entries at once by specifying a matrix, or matrices of indices or use the : operator to extract all entries along a certain dimension. The ‘end’ statement stands for the last index of a dimension.
Logical Indexing
We can also extract entries using a bit pattern, i.e. a matrix of logical values. Only the entries corresponding to true are returned. This can be particularly useful for selecting elements that satisfy some logical criteria such as being larger than a certain value. We can create a logical matrix by relating a numeric matrix to either a scalar value or matrix of the same size via one of the logical operators, < > <= >= ==
= or by a binary function such as isprime() or isfinite().
We can then use this logical matrix to extract elements from A. In the following line, we repeat the call to A > 30 but pass the result directly in, without first storing the interim result.
We could also achieve the same result using the find() function, which returns the indices of all of the non-zero elements in a matrix. While this command is useful when the indices themselves are of interest, using find() can be slightly slower than logical indexing although it is a very common code idiom.
We can check that two matrices are equal, (i.e. the same size with the same elements) with the isequal() function. Using the == relation returns a matrix of logical values, not a single value.
Assignment
Assignment operations, in which we change a value or values in a matrix, are performed in a very similar way to the indexing operations above. Both parallel and logical indexing can be used. We indicate which entries will be changed by performing an indexing operation on the left hand side and then specify the new values on the right hand side. The right must be either a scalar value, or a matrix with the same dimensions as the resulting indexed matrix on the left. Matlab automatically expands scalar values on the right to the correct size.
We can assign every value at once by using the colon operator. The following command temporarily converts A to a column vector, assigns the values on the right hand side and converts back to the original dimensions.
Recall from the indexing section that indices can be repeated returning the corresponding entry multiple times as in A([1,1,1],3). You can also repeat indices in assignments but the results are not what you might expect.
You may have expected the entry A(1,1) to now have a value of 4 instead of 2 since we indexed entry A(1,1) three times. Matlab calculates the right hand side completely before assigning the values and so the value of 2 is simply assigned to A(1,1) three times.
Deletion
Assigning [] deletes the corresponding entries from the matrix. Only deletions that result in a rectangular matrix are allowed.
Expansion
When the indices in an assignment operation exceed the size of the matrix, Matlab, rather than giving an error, quietly expands the matrix for you. If necessary, it pads the matrix with zeros. Using this feature is somewhat inefficient, however, as Matlab must reallocate a sufficiently large chunk of contiguous memory and copy the array. It is much faster to preallocate the maximum desired size with the zeros command first, whenever the maximum size is known in advance: see here for details.
Linear Indexing
When only one dimension is specified in an indexing or assignment operation, Matlab performs linear indexing by counting from top to bottom and then left to right so that the last entry in the first column comes just before the first entry in the second column.
The functions ind2sub() and sub2ind() will convert from a linear index to regular indices and vice versa, respectively. In both cases, you must specify the size of the underlying matrix.
Sometimes, when dealing with multi-dimensional arrays, it is annoying that these functions return/ require multiple separate arguments. We therefore provide the following alternative functions: ind2subv and subv2ind
Reshaping and Replication
It is sometimes useful to reshape an array of size m-by-n to size p-by-q where m*n = p*q. The reshape() function lets you do just that. The elements are placed in such a way so as to preserve the order induced by linear indexing. In other words, if a(3) = 3 before reshaping, a(3) will still equal 3 after reshaping.
Further, the repmat() function can be used to tile an array m-by-n times.
Element-Wise Matrix Arithmetic
We can perform the arithmetical operations, addition, subtraction, multiplication, division, and exponentiation on every element of a matrix. In fact, we can also use functions such as sin(), cos(), tan(), log() , exp() , etc to operate on every entry but we will focus on the former list for now.
If one operand is a scalar value, an element-wise operation is automatically performed. However, if both operands are matrices, a dot must precede the operator as in .* , .^ , ./, and further, both matrices must be the same size.
Matlab also has the .\ operator which is the same as the ./ operator with the order of the operands reversed so that (A ./ B) = (B .\ A). As this is infrequently used, it should be avoided for the sake of clarity.
Matrix Multiplication
We can also perform matrix multiplication of an m-by-n matrix and an n-by-p matrix yielding an m-by-p matrix. Suppose we multiple A*B = C, then C(i,j) = A(i,:)*B(:,j) , that is, the dot product of the ith row from A and the jth column from B. The dot, (or inner) product of a and b is just sum(a.*b). Further, if A is a square matrix, we can multiply A by itself k times by the matrix exponentiation A^k.
Solving linear systems
Suppose we have the matrix equation Y = XW where X is an n-by-d matrix, W is a d-by-k matrix and thus Y is an n-by-k matrix. If X is invertible, we could solve for W= inv(X)*Y. The inv() function returns the inverse of a matrix. If n
= d, however, we can still solve for the least squares estimate of W by taking the pseudo inverse of X, namely inv(X’*X)*X’, or more concisely using the Matlab function, pinv(X). Matlab allows you to solve more directly, (and efficiently) for W, (i.e. the lsq estimate of W), however, by using the matrix division X \ Y. Both X and Y must have the same number of rows. (Below we specify a seed to the random number generators so that they return the same values every time this demo is run).
Matlab also supports matrix right division such that X \ Y = (Y’ / X’)’ but as this is infrequently used, it should be avoided for the sake of clarity.
More Linear Algebra
Matlab was original designed primarily as a linear algebra package, and this remains its forte. Here we only list a few functions for brevity, do not display the results. Many functions can also take additional arguments: type doc svd for instance to see documentation for the svd() function.
Multidimensional Arrays
Numeric matrices in Matlab can extend to an arbitrary number of dimensions, not just 2. We can use the zeros(), ones(), rand(), randn() functions to create n-dimensional matrices by simply specifying n parameters. We can also use repmat() to replicate matrices along any number of dimensions, or the cat() function, which is a generalization of the [] concatenation we saw earlier. Indexing, assignment,and extension work just as before, only with n indices, as opposed to just two. Finally, we can use functions like sum(), mean(), max() or min() by specifying the dimension over which we want the function to operate. sum(A,3) for example, sums over, or marginalizes out, the 3rd dimension.
Taking the mean of say a 4-by-4-by-2-by-2 matrix along the 3rd dimension results in a matrix of size 4-by-4-by-1-by-2. If we want to remove the 3rd singleton dimension, (which is only acting now as a place holder) we can use the squeeze() function.
The ndims() functions indicates how many dimensions an array has. Final singleton dimensions are ignored but singleton dimensions occurring before non-singleton dimensions are not.
The meshgrid() function we saw earlier extends to 3 dimensions. If you need to grid n-dimensional space, use the ndgrid() function but keep in mind that the number of elements grows exponentially with the dimension.
Sparse Matrices
When dealing with large matrices containing many zeros, you can save a great deal of space by using Matlab’s sparse matrix construct. Sparse matrices can be used just like ordinary matrices but can be slower depending on the operation. The functions full() and sparse() convert back and forth. Currently Matlab supports double and logical sparse matrices.
The spy() function can be used to visualize the sparsity pattern of a matrix.
The spalloc() function can be used to preallocate space for a sparse matrix. The following command creates a 100-by-100 matrix with room currently for 10 non-zero elements. More than 10 non-zero elements can be added later but this can be slow as Matlab will need to find a larger chunk of memory and copy the non-zero elements.
Other numeric data types
Matlab has limited support for 11 numeric data types similar to those in the C programming language. Below we create matrices of each type and show the space each matrix requires. Matrices can also be created by using the commands int8() , single() , int64() etc. The cast() command, converts from one data type to another. You can determine the class of a variable with the class() command and the maximum or minimum values each class is able to represent with the intmax() , intmin() , realmax() , and realmin() functions. The uint classes are unsigned and not able to represent negative numbers. Unfortunately many Matlab functions do not support types other than double or logical. Functions such as sum() have an optional parameter ‘native’, which performs summation without automatically casting to double. To perform variable precision arithmetic, check out the vpa() function available in the symbolic math toolbox.
Other Useful Functions
The cumsum() and cumprod() functions can be useful for generating a running sum or product of an array. The diff() function returns the differences between consecutive elements. You can specify the dimension over which you want them to operate. If you leave this blank, they operate over the first non-singleton dimension.
The histc function is useful for, (among other things) counting the number of occurrences of numbers in an array.
The filter() function can be used to calculate values that depend on previous values in an array. While it is quite a complicated function, here is an easy way to calculate the points halfway between each consecutive point in an array. The first result is just half the value of the first element. You can calculate a running average in which only a window of k elements are included with filter(ones(1,k)/k,1,data).