How to index a matrix to make it from a vector, taking some elements from the vector and put them in a new row?

1 vue (au cours des 30 derniers jours)
I need to construct a matrix taking three elements from a 14-elements vector v(1:3) and write them in a row, then take the next three elements v(2:4) in the next row, and so on. Such that that I need to have something as in the image:
I have this piece of code but the indexing is no correct:
pilots4356 = Rxc1(43:56); %vector
matrix4356 = zeros(12,14); %matrix size
pospilot = 1; %index
for f = 1:12 %rows
for c = 1:14 %columns
for pospilot = pospilot:pospilot+2
matrix4356(:,c) = pilots4356(pospilot);
end
pospilot = pospilot+1;
end
end
matrix4356

Réponse acceptée

Voss
Voss le 28 Nov 2022
Here's one way to do it:
pilots4356 = 43:56; %vector
N = numel(pilots4356)-2;
matrix4356 = zeros(N,N+2); %matrix size
% place the vector along the diagonals of the matrix:
matrix4356(1:N+1:N^2) = pilots4356(1:end-2);
matrix4356(N+1:N+1:N^2+N) = pilots4356(2:end-1);
matrix4356(2*N+1:N+1:N^2+2*N) = pilots4356(3:end);
disp(matrix4356);
43 44 45 0 0 0 0 0 0 0 0 0 0 0 0 44 45 46 0 0 0 0 0 0 0 0 0 0 0 0 45 46 47 0 0 0 0 0 0 0 0 0 0 0 0 46 47 48 0 0 0 0 0 0 0 0 0 0 0 0 47 48 49 0 0 0 0 0 0 0 0 0 0 0 0 48 49 50 0 0 0 0 0 0 0 0 0 0 0 0 49 50 51 0 0 0 0 0 0 0 0 0 0 0 0 50 51 52 0 0 0 0 0 0 0 0 0 0 0 0 51 52 53 0 0 0 0 0 0 0 0 0 0 0 0 52 53 54 0 0 0 0 0 0 0 0 0 0 0 0 53 54 55 0 0 0 0 0 0 0 0 0 0 0 0 54 55 56

Plus de réponses (1)

Stephen23
Stephen23 le 29 Nov 2022
A general approach:
V = 43:56;
N = 3;
C = numel(V);
M = V .* tril(triu(ones(C-N+1,C)),N-1);
disp(M)
43 44 45 0 0 0 0 0 0 0 0 0 0 0 0 44 45 46 0 0 0 0 0 0 0 0 0 0 0 0 45 46 47 0 0 0 0 0 0 0 0 0 0 0 0 46 47 48 0 0 0 0 0 0 0 0 0 0 0 0 47 48 49 0 0 0 0 0 0 0 0 0 0 0 0 48 49 50 0 0 0 0 0 0 0 0 0 0 0 0 49 50 51 0 0 0 0 0 0 0 0 0 0 0 0 50 51 52 0 0 0 0 0 0 0 0 0 0 0 0 51 52 53 0 0 0 0 0 0 0 0 0 0 0 0 52 53 54 0 0 0 0 0 0 0 0 0 0 0 0 53 54 55 0 0 0 0 0 0 0 0 0 0 0 0 54 55 56

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by