Extract columns and rows from matrix

I need to extract a column (let's say 1st) from 1st matrix (5x5) to use it as a row (let's say 5th) in a 2nd matrix (5x5).
Thanks in advance

 Risposta accettata

Torsten
Torsten il 4 Nov 2023
Spostato: Torsten il 4 Nov 2023
first = rand(5)
first = 5×5
0.6556 0.1094 0.2522 0.5119 0.5134 0.4183 0.3149 0.5010 0.4793 0.0783 0.9219 0.1391 0.7669 0.4079 0.2564 0.3306 0.2384 0.4618 0.3429 0.0067 0.3400 0.3090 0.4482 0.6066 0.5850
second = rand(5)
second = 5×5
0.7720 0.9819 0.2196 0.4291 0.6845 0.8561 0.0148 0.9716 0.8685 0.8155 0.3618 0.2091 0.7744 0.6708 0.5010 0.1139 0.4576 0.3263 0.4784 0.1249 0.3806 0.5838 0.4502 0.5900 0.5781
second(5,:) = first(:,1).'
second = 5×5
0.7720 0.9819 0.2196 0.4291 0.6845 0.8561 0.0148 0.9716 0.8685 0.8155 0.3618 0.2091 0.7744 0.6708 0.5010 0.1139 0.4576 0.3263 0.4784 0.1249 0.6556 0.4183 0.9219 0.3306 0.3400

7 Commenti

Much appreciated!!
Note that the TRANSPOSE is optional:
first = rand(5)
first = 5×5
0.2622 0.9271 0.8045 0.4209 0.9297 0.1965 0.1722 0.4752 0.5092 0.2747 0.5255 0.8954 0.8495 0.5751 0.1948 0.5142 0.3306 0.3673 0.1700 0.1440 0.1852 0.6967 0.2868 0.3201 0.3975
second = rand(5)
second = 5×5
0.0998 0.1903 0.2646 0.7202 0.6271 0.3664 0.1022 0.9504 0.5349 0.1289 0.7642 0.0478 0.2630 0.9633 0.7535 0.5964 0.9338 0.9450 0.4532 0.1578 0.8699 0.7766 0.4579 0.5648 0.2570
second(5,:) = first(:,1)
second = 5×5
0.0998 0.1903 0.2646 0.7202 0.6271 0.3664 0.1022 0.9504 0.5349 0.1289 0.7642 0.0478 0.2630 0.9633 0.7535 0.5964 0.9338 0.9450 0.4532 0.1578 0.2622 0.1965 0.5255 0.5142 0.1852
Interesting that MATLAB doesn't differ between row and column in this case. Why is it ?
@Torsten that is because the number of elements in L.H.S is equal to the R.H.S
@madhan ravi, then this should work as well, but it doesn't.
y = rand(5,5)
y = 5×5
0.2054 0.3064 0.3352 0.1937 0.8819 0.9259 0.3211 0.8781 0.5697 0.8578 0.3453 0.2379 0.6059 0.2627 0.2939 0.5965 0.9375 0.1124 0.3127 0.4328 0.2790 0.7215 0.9603 0.4169 0.3628
y([2 3], :) = y(:, [2 3])
Unable to perform assignment because the size of the left side is 2-by-5 and the size of the right side is 5-by-2.
An explaination (or definition) is provided in the documentation of subsasgn -
For multidimensional arrays, A(i,j,k,…) = B assigns B to the specified elements of A. B must be length(i)-by-length(j)-by-length(k)-… or be shiftable to that size by adding or removing singleton dimensions.
1xN is shiftable to Nx1 by removing the 1st singleton dimesion.
1xN == 1xNx1 -> Nx1
Thank you for the explanation.

Accedi per commentare.

Più risposte (0)

Prodotti

Tag

Richiesto:

il 4 Nov 2023

Commentato:

il 5 Nov 2023

Community Treasure Hunt

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

Start Hunting!

Translated by