Как транспонировать матрицу в матлаб
Перейти к содержимому

Как транспонировать матрицу в матлаб

  • автор:

4.1. Использование матриц в matlab.

Базовой структурой данных в MATLAB является матрица (matrix): двухмернaя, имеющая прямоугольную форму структура данных, в которой хранится набор элементов данных в простом и легко доступном формате. Эти элементы данных могут быть числами, символами, логическими единицами true или false, или даже другими типами структур данных MATLAB. В MATLAB используются двухмерные матрицы для хранения отдельных чисел, а также, линейных последовательностей данных. В этих случаях размерности 1×1 и 1×n, соответственно, где n – длина числовой последовательности. MATLAB также поддерживает структуры данных, которые имеют больше чем два измерения. В MATLAB эти структуры данных имеют название arrays (массивы). MATLAB является вычислительной средой, основой которой является матрица. Все вводимы в MATLAB данные хранятся в форме матрицы или многомерного массива.

4.1.1. Создание матриц и базовые матричные операции.

Матрица – это двух мерный массив вещественных или комплексных чисел. В MATLAB имеется ряд функций, которые позволяют создавать различные типы матриц. Простейший способ создания матрицы в MATLAB – использовать оператор констора матрицы, []. Этот оператор создает строку в матрице при вводе элементов (показаны ниже как E) в скобках. Каждый элемент необходимо отделять запятой или пробелом:

row = [E1, E2, . Em] row = [E1 E2 . Em]

Например, для того, чтобы создать матрицу из пяти элементов, напечатайте

A = [12 62 93 -8 22];

Для того, чтобы начать новую строку, надо закончить текущую точкой с запятой:

A = [row1; row2; . ; rown]

В этом примере вводится матрица, состоящая из 3-х строк и 5-и столбцов ( 3×5) чисел. Все строки должны иметь одинаковое число элементов,

A = [12 62 93 -8 22; 16 2 87 43 91; -4 17 -72 95 6]

Этот оператор констора матрицы может создавать только двухмерные матрицы (включая 0×0, 1×1, 1×n,).

Специализированные матричные функции.

Создает матрицу или массив, состоящий из всех единиц

Создает матрицу или массив, состоящий из всех нулей

Создает матрицу с единицами на диагонали и остальными нулями

Распределяет элементы входной матрицы в соответствии с заданным положением в выходной матрице

Преобразует вектор в диагональную матрицу

Создает квадратную матрицу, в которой сумма элементов строк, или элементов столбцов, или элементов главных диагоналей одинакова

Создает матрицу или массив случайных чисел имеющих равномерное распределнием

Создает матрицу или массив случайных чисел или случайных массивов имеющих нормальное распределнием

Создает вектор (1-на-n матрицу) содержащий случайное размещение заданного числа целых

Например, для создания волшебной квадратной матрицы 5×5 воспользумся функцией magic,

Конкатенация (объединение) матриц.

Матричная конкатенация – это объединение одной или большего числа матриц, для получения новой матрицы. Скобки [] используются не только как конструктор матрицы, но также как оператор конкатенации. Результатом выражения C = [A B] является конкатенация матриц A и B по горизонтали. Результатом выражения C = [A; B] является конкатенация матриц A и B по вертикали. This example constructs a new matrix C by concatenating matrices A and B in a vertical direction:

A = ones(2, 5) * 6; % матрица 2×5 все элементы которой равны 6

B = rand(3, 5); % матрица 3×5 состоящая из случайных чисел

C = [A; B] % конкатенация матриц A и B по вертикали

Функции матричной конкатенации

Конкатенация матриц вдоль заданного направления

Конкатенация матриц по горизонтали

Конкатенация матриц по вертикали

Конкатенация матриц по горизонтали и по вертикали

Создания блочной диагональной матрицы из существующих матриц

Генерирование числовых последовательностей, оператор двоеточие (:).

Оператор двоеточие (first:last) генерирует матрицу 1×n (или вектор) последовательных чисел от первого числа до последнего. По умолчанию получаем последовательность чисел, увеличивающихся на единицу, каждое последующее на 1 больше предыдущего.

10 11 12 13 14 15

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

-2.5000 -1.5000 -0.5000 0.5000 1.5000 2.5000

Для генерирования числовых последовательностей с шагом, отличным от 1, оператор двоеточие может использоваться со указанием величины приращения элементов (first:step:last). Величина step указывает шаг приращения (уменьшения, если step является отрицательным числом) элементов последовательности чисел. Например,

10 15 20 25 30 35 40 45 50

Шаг может быть дробным или отрицательным числом,

3.0000 3.2000 3.4000 3.6000 3.8000

9 8 7 6 5 4 3 2 1

Индексация матриц.

Для доступа к отдельному элементу матрицы задайте номер строки и номер столбца используя следующу запись A(n, m), где A – матричная переменная. Номер столбца всегда указывается первым, а номер столбца – втрым, например,

для доступа к элементу в 4-й строке, 2-й колонке напечатайте

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

Линейная индексация матриц. Вы можете обращаться к элементу матрицы используя единственный индекс, A(k). MATLAB хранит матрицы и массивы не в той форме, в которой они появляются в командном окне, а как единый столбец элементов. Этот единый столбец составлен из столбцов матрицы, каждый столбц присоединяется к предыдущему. Так, матрица A

A = [2 6 9; 4 2 8; 3 5 1]

в действительности хранится в памяти как последовательность

2, 4, 3, 6, 2, 5, 9, 8, 1

Элемент с строке 3, столбец 2 матрицы A (значение = 5) может быть идентифицирован как элемент 6 в действительной хранимой последовательности. Для доступа к этому элементу, есть возможность использовать стандартный синтаксис A(3,2), или есть возможность применить A(6), относящуюся к линейной индексации.

Обращение к последовательности элементов. Для матрицы A размерности 4×4, сумму элементов 4-го столбца можно вычислить набрав

A(1,4) + A(2,4) + A(3,4) + A(4,4)

Можно уменьшить размер выражения используя оператор двоеточие. Индексные выражения, включающие двоеточия, обращаются к последовательности элементов матрицы. Выражение,

обращается к элементам в строках с 1-й по m-ю, n-го столбца матрицы A. Используя эту запись, можно вычислить сумму элементов 4-го столбца матрицы A более компактно:

Обращение к элементам, которые не следуют друг за другом. Для этого используйте оператор двоеточия с величиной шага. Выражение m : 3 : n означает обращение к каждому третьему элементу матрицы. При линейной индексации имеем:

MATLAB поддерживает тип индексации массивом, при которой один массив используется как индекс в другом массиве. Этот тип индексации может быть основан на задании в массиве индексов либо номеров, либо размещения элементов. В приведенном ниже примере массив B состоит из индексов 1, 3, 6, 7, и 10 массива A. В этом случае, числовые значения элементов массива B соответствуют положению элементов в массиве A:

5 10 15 20 25 30 35 40 45 50

Ключевое слово end (конец). MATLAB предоставляет ключевое слово end для доступа к последнему элементу массива. В предыдущем примере можно использовать запись

Описание всех элементов строки или столбца. Двоеточие само по себе относится ко всем элементам строки или столбца матрицы. Используя следующую запись может быть вычислена сумма элементов во 2-м столбце волшебной квадратной 4×4 матрицы A:

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

Получение информации о матрице.

Функции, возвращающие информации о форме матрицы.

Возвращает величину самой длинной размерности

Возвращает число размерностей

Возвращает число элементов

Возвращает длину каждой размерности

Изменение размерности и формы матриц.

Способы увеличения размерности матрицы.

• Конкатенация новых элементов

• Размещение элементов за границами матрицы

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

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

Пример. Дана матрица 3×5,

A = [ 10 20 30 40 50; .

60 70 80 90 100; .

110 120 130 140 150];

ее необходимо дополнить 4-й строкой. Разместим новый элемент в 1-м столбце не существующей 4-й строки исходной матрицы. MATLAB расширит матрицу A добавлением новой 4-й строки, заполнив нулями колонки со 2-й по 5-ю.

60 70 80 90 100

110 120 130 140 150

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

Пример. Дана матрица 4×4,

из нее необходимо удалить 2-й столбец,

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

в результате получим:

16 9 3 6 13 12 1

Функции, изменяющие форму матрицы

Изменяет форму матрицы

Вращает матрицу на 90 градусов

Поворачивает матрицу относительно вертикальной оси

Поворачивает матрицу относительно горизонтальной

Поворачивает матрицу относительно заданного направления

Поворачивает матрицу относительно ее главной диагонали, заменяя вектора-строки на вектора-столбцы, и наоборот

Транспонирует матрицу и заменяет каждый элемент комплексно-сопряженным

Примеры применения функций, изменяющих форму матрицы.

Используя матрицу А, имеющую размерность 3×4 построить матрицу В размерности 2×6:

A = [1 4 7 10; 2 5 8 11; 3 6 9 12]

B = reshape(A, 2, 6)

Для транспонирования матрицы можно использовать как функцию transpose, так и оператор (.’)s:

Скаляры. Скалярная величина – это любое отдельное вещественное или комплексное число, которое представлено в MATLAB как матрица размерности 1×1:

Функция isscalar определяет, содержит ли переменная скалярную величину:

Векторы. Вектор – это матрица, одина из размерностей которой равна единице, а другие больше единицы. Пример числового вектора-строки:

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).

Transpose Matrix Matlab

By Priya PedamkarPriya Pedamkar

Transpose Matrix Matlab

Introduction to Transpose Matrix Matlab

In this article, we will learn about Transpose Matrix Matlab. If output matrix rows are equal to input columns and output matrix columns are equal to rows of the input matrix then the output matrix is called ‘transpose of the matrix’. This ‘T’ represents the transpose of the matrix. Let us consider there are two matrices one is the input matrix ‘I’ and the second is the output matrix ‘O’. A number of rows of the input matrix are ‘Irow’. The number of columns in the input matrix is ‘Idol’ and the number of rows in the output matrix is ‘Orow’. Number of columns in output matrix is ‘Ocol’ then Transpose of matrix satisfies two conditions which are Icol=Orow and Irow=Ocol.(rows of input matrix =column of output matrix and columns of input matrix=rows of output matrix)

How We Can Do Transpose Matrix in Matlab?

There are two ways to find out transpose of a matrix in Matlab which are:

Hadoop, Data Science, Statistics & others

  1. By Using Operator
  2. By Using Command
1. By Using Operator

In this method, the dot operator is used to finding the transpose of the matrix (. ’). This is one of the easiest and simple methods for transpose. The only limit of this method is there are high chances of syntax error because of the operator.

Syntax:

Output matrix=input matrix . ’

Steps:

  • Accept input matrix by using square matrix (Input = [ 23 , 32 , 11 ; 22 3 2 ; 16 39 21 ; 32 4 1 ]
  • Apply the operator on the input matrix ( output matrix=input matrix.’)
  • Display the output matrix.
2. By Using Command

In this method, ‘transpose’ command is used to find out the transpose of the matrix. This method is less complex and easy to implement as compared to the previous method. And there are fewer chances of error at the time of implementation.

Syntax:

Output matrix=transpose (input matrix)

Steps:

  • Accept input matrix by using square matrix (Input = [ 23 , 32 , 11 ; 22 3 2 ; 16 39 21 ; 32 4 1 ]
  • Apply command on input matrix ( output matrix = transpose (input matrix))
  • Display output matrix.

Examples for Transpose Matrix Matlab

Following are the examples implement the matrix Matlab:

Example #1

Let us consider the input matrix as mat1;
Code:
mat1 =
23 32 11
22 3 2
16 39 21
32 4 1
The following table illustrates the Matlab code for example 1 by using the operator.

mat1 = [ 23 , 32 , 11 ; 22 3 2 ; 16 39 21 ; 32 4 1 ] mat3 = mat1 . ‘

How to take Matlab Transpose – Syntax and Examples

This tutorial is about the Matlab Transpose operator. Let’s first understand the term ‘transpose’. The transpose of a matrix is an operator which switches rows with columns and vice versa. It can be also applied to a row vector or a column vector. Using the transpose operator, we can convert a row vector into a column vector and a column vector into a row vector. Suppose we have a row vector x = [1 7 3].

Please enable JavaScript

On applying the transpose operator, it becomes a column vector. If the transpose operator is applied again, then this column vector becomes a row vector. Similarly, when the transpose is applied to the matrix, the elements are flipped over its diagonals. Consider a 3 X 3 matrix A which is equal to:

Applying transpose on matrix A gives a 3 x 3 output matrix (O)which is produced by interchanging rows into columns and interchanging columns into rows.

In Matlab, there are three ways to take the transpose of a matrix which are:

  • Dot operator
  • using transpose() function
  • using for loop
Method 1: Using Dot Operator

The first method uses a dot operator (.’) to find the transpose. The syntax is given below:

The operator when applied on input return a resultant output vector or matrix whose number of rows is equal to the number of columns of the input vector or matrix and the number of columns is equal to the number of rows in the input vector or matrix.

Example 1:

For a vector or matrix with complex numbers, the (‘) operator interchanges rows with columns and generate the complex conjugate vector or a matrix in which the sign of the imaginary part of each complex element changes. Let’s understand this by a simple example.

Example 2:

Consider the complex matrix A.

Output: />

You can observe from the output on applying (‘) operator on the matrix A, the signs of imaginary parts of all the elements are reversed. If you only want to transpose of a complex matrix, then use (‘) this operator along with a dot operator. Consider the same example.

Example 3:

Observing the output only rows and columns are interchanged. The sign of imaginary parts remains the same as in the input matrix. The (.) operator is the simplest and easiest approach to find the transpose but there are high chances of syntax error in using this operator

Method 2: Using Transpose function

The MATLAB has a built-in transpose function which when applied on any vector or matrix, it directly computes and returns the transpose of a matrix. The syntax is given below.

The function takes an input vector or a matrix as an argument and returns the transpose.

Example 4:

Output: />

There is another built-in function “ctranspose” which returns the complex conjugate transpose of a matrix.

Example 5:

Method 3: Using for loop

The third method of taking transpose is by using for loop. Create and initialize a matrix [Aij] whose transpose is to be calculated. Then create another zero matrix of size [Bji] to store the transpose of matrix A. Write a code of for loop which will iterate through rows and columns one by one and will replace the contents of Bji with Aij.

The following example demonstrates how using for-loop, you can find the transpose.

In the above example, you will observe that the matrix ‘res’ is initialized by first calculating the size of the input matrix i.e., x using the command “size(x)”. The size(x) command returns the number of rows and number of columns of matrix ‘x’ where variable ‘m’ represents a number of rows and variable ‘n’ indicates the number of columns. Then ‘res’ matrix is created by passing variable ‘n’ in a number of rows and ‘m’ in a number of columns. Then the for loop iterates through rows and columns and inserts the values.

In this article, we have seen how to find out the transpose of a vector or matrix by using different methods. Let us know if you have any queries regarding this topic. Your review matters to us a lot. Please let us know your feedback in the comments.

Добавить комментарий

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