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

1 次查看(过去 30 天)
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.

采纳的回答

Voss
Voss 2024-4-20
编辑:Voss 2024-4-20

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 个评论
Saki
Saki 2024-4-20
编辑:Saki 2024-4-24
I got the things what i want.
No need to assign a initial empty A 3d matix.
Voss
Voss 2024-4-20
编辑:Voss 2024-4-20
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by