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

1 view (last 30 days)
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.

Accepted Answer

Voss
Voss on 20 Apr 2024
Edited: Voss on 20 Apr 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 Comments
Saki
Saki on 20 Apr 2024
Edited: Saki on 24 Apr 2024
I got the things what i want.
No need to assign a initial empty A 3d matix.
Voss
Voss on 20 Apr 2024
Edited: Voss on 20 Apr 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!