3d matrix initialization and find the specific values after the for loops

1 visualización (últimos 30 días)
Hello my Vf is 42444 *1*1000 matrix. I used this code for finding values for the location of 312 and incrementing of 324 from the 42444 values. But why the final matrix A is 131 * 3*1000. I am expecting 131*1*1000.

Respuesta aceptada

Voss
Voss el 20 de Abr. de 2024
Editada: Voss el 20 de Abr. de 2024

You give A three columns when you do this:

A=[m,n,p]; % size 1x3

Perhaps you meant:

A=zeros([m,n,p]);

But that would give A too many rows.

Anyway, the whole thing can be done in one line:

A = Vf(312:324:end,:,:);
  2 comentarios
Saki
Saki el 20 de Abr. de 2024
Editada: Saki el 24 de Abr. de 2024
I got the things what i want.
No need to assign a initial empty A 3d matix.
Voss
Voss el 20 de Abr. de 2024
Editada: Voss el 20 de Abr. de 2024
It's a good idea to clear (if in a script) or preallocate A before your loops.
Or avoid all of that and do:
A = Vf(312:324:end,:,:);
Demonstration:
Loop method
% Vf= is a 3d matix of 42444 * 1 * 1000;
Vf = rand(42444,1,1000);
tic
m = size(Vf, 1);
n = size(Vf, 2);
p = size(Vf, 3);
for j = 1:p
index = 1;
for i = 312:324:m
% Assign the value from Vf to the corresponding location in A
A(index, :, j) = Vf(i, :, j);
index = index + 1;
end
end
toc
Elapsed time is 0.176245 seconds.
Direct method
tic
A_test = Vf(312:324:end,:,:);
toc
Elapsed time is 0.002738 seconds.
The result is the same
isequal(A,A_test)
ans = logical
1
and the "Direct" method is much simpler code and about 65 times faster.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by