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

1 回表示 (過去 30 日間)
Saki
Saki 2024 年 4 月 20 日
編集済み: Saki 2024 年 4 月 24 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by