How can I add an extra dimension to make the array 2D to 3D?

19 ビュー (過去 30 日間)
Gulfam Saju
Gulfam Saju 2022 年 5 月 13 日
コメント済み: Jan 2022 年 5 月 17 日
clear all;
for idx = 1:258
name = '';
if idx < 10
name = strcat('0',int2str(idx),'.mat');
load(name);
else
name = strcat(int2str(idx),'.mat');
load(name);
end
data=sqrt(sum([abs(raw_data)].^2,3));
%data = (data,idx)
save("01_new.mat", "data")
end
There are 258 mat files( named as "01.mat" to "258.mat") in the folder. So I am running the loop upto 258. All the mat files contain different image, but has the same data structure 320*320*16.
Then I removed one dimension using sum of square.
Now, I am trying to add 3rd dimension in the "data" see the commented line. The third dimension will contain the mat file number from the folder.
Then finally I want to stack all the 258 files into one ".mat" file.

採用された回答

Jan
Jan 2022 年 5 月 13 日
編集済み: Jan 2022 年 5 月 13 日
Reduce the clutter:
name = '';
if idx < 10
name = strcat('0',int2str(idx),'.mat');
load(name);
else
name = strcat(int2str(idx),'.mat');
load(name);
end
Smarter:
name = sprintf('%0d.mat', idx);
This fills in a leading zeros on demand.
Do no load data directly into the workspace, because this can cause unexpected side-effects. Catch the output of load() in a variable instead.
[] is Matlab's operator for the concatenation of arrays. In [abs(raw_data)] you concatenate the output of the abs() command with nothing. Simply omit the square brackets.
clear all removes all loaded functions from the memory. Reloading them from the slow disk wastes a lot of time. There are no further benefits of this command, so simply omit it.
It is safer to specify files with a full path. Relying on the current folder is fragile, e.g. when a callback of a GUI or timer changes the current folder. This is so hard to debugm, that it is a good programming practice to use full paths in general.
Summary:
Folder = cd; % Or better define the folder explicitly
Result = zeros(320, 320, 258);
for idx = 1:258
File = fullfile(Folder, sprintf('%0d.mat', idx));
Data = load(File);
Result(:, :, idx) = sqrt(sum(Data.raw_data .^ 2, 3));
end
save(fullfile(Folder, '01_new.mat'), 'Result');
Are the value of the raw_data real? Then there is no need for the abs() command, because the elementwise squaring .^2 removes the sign also.
  4 件のコメント
Gulfam Saju
Gulfam Saju 2022 年 5 月 17 日
Can you please suggest, How can I do that for a single file?
Jan
Jan 2022 年 5 月 17 日
How can you do what for a single file?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by