How to index first element of an arbitary sized matrix?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Joseph Hansen-Shearer
el 8 de Nov. de 2023
Comentada: Stephen23
el 8 de Nov. de 2023
I have a matrix and I need to index the first dimension but I don't know the size of the matrix. Is there a way to do this in a generic way rather than hard code each case. I am aware I could do this with eval but I try and steer clear of using this function where possible.
Example:
ind_left = 25;
ind_right = 66;
% For a 2-D matrix it would be this
A = rand(100,100); % sample 3-D input matrix
B = A(ind_left:ind_right,:);
% For a 3-D matrix it would
A = rand(100,100,100); % sample 3-D input matrix
B = A(ind_left:ind_right,:,:);
% For a 4-D matrix it would be ...
3 comentarios
Stephen23
el 8 de Nov. de 2023
@Joseph Hansen-Shearer: thank you for noticing that, I fixed my comment!
Respuesta aceptada
Dyuman Joshi
el 8 de Nov. de 2023
Editada: Dyuman Joshi
el 8 de Nov. de 2023
%Example
ind_left = 25;
ind_right = 45;
vec = ind_left:ind_right;
n = 5;
A = rand(50*ones(1,n)); % sample n-D input matrix
size(A)
%Manually
B = A(vec,:,:,:,:);
size(B)
%Generalised method
C = reshape(A(vec,:),[numel(vec) size(A, 2:ndims(A))]);
size(C)
%Check for equality
isequal(B,C)
3 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!