フィルターのクリア

Sorting Struct elements in Numerical order

9 ビュー (過去 30 日間)
Md Farhad Mokter
Md Farhad Mokter 2019 年 6 月 6 日
コメント済み: Stephen23 2021 年 5 月 4 日
I have a program which takes some pictures in a struct and performs some pixel counting in each of the pictures. After running the program when I see the struct, the elements are not arranged in the way I want them to be. Here is the code-
img_folder = ('C:\Users\mm\work\blackpixelcount');
filenames = dir(fullfile(img_folder,'*.JPG'));
Total_image = numel(filenames);
for i= 1:Total_image
f = fullfile(img_folder,filenames(i).name);
im= imread(f);
bw= imbinarize(im);
out=nnz(~bw);
get(i)=out;
end
after running the code I see the struct and its sorted as given below-
x.JPG
Now I want the elements to be sorted in numerical ascending order (1,2,3.....9,10,11,12..).
I might be makigs some mistakes there, since I am biggener in matlab. Help will be really appreciated.
  1 件のコメント
Stephen23
Stephen23 2021 年 5 月 4 日
Note that NATSORTFILES now directly sorts the structure returned by DIR:
S = dir(..);
S = natsortfiles(S);

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

採用された回答

KSSV
KSSV 2019 年 6 月 6 日
  9 件のコメント
Stephen23
Stephen23 2019 年 6 月 6 日
編集済み: Stephen23 2019 年 6 月 6 日
"But the 'filenames' variable remained same as before"
Sure. You only define it once (on the second line of your code), nowhere else in your code do you make any changes to filenames. You assigned the output of natsortfiles to variable b, so b contains the sorted filenames.
Follow the examples in the natsortfiles documentation.
Jan
Jan 2019 年 6 月 6 日
編集済み: Jan 2019 年 6 月 6 日
@Md Farhad Mokter: Use this:
img_folder = ('C:\Users\mm\work\blackpixelcount');
filelist = dir(fullfile(img_folder,'*.JPG'));
filenames = {filelist.name}; % added
b = natsortfiles(filenames);
Total_image = numel(b);
getList = zeros(1, Total_image); % Pre-allocate, avoid "get" as name
for i = 1:Total_image
f = fullfile(img_folder, b{i}); % not b(i).name
im = imread(f);
bw = imbinarize(im);
getList(i) = nnz(~bw);
end
get is an important Matlab command, so avoid using it as name of a variable.

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

その他の回答 (1 件)

Md Farhad Mokter
Md Farhad Mokter 2019 年 6 月 6 日
it worked !!
After reading the documentation part once again, I edited the code in line 3 and line 4.
img_folder = ('C:\Users\mm\work\blackpixelcount');
filenames = dir(fullfile(img_folder,'*.JPG'));
[~,ndx] = natsortfiles({filenames.name});
filenames = filenames(ndx);
Total_image = numel(filenames);
for i= 1:Total_image
f = fullfile(img_folder,filenames(i).name);
im= imread(f);
bw= imbinarize(im);
out=nnz(~bw);
get(i)=out;
end
Now It is all good. My apologies for mistakes and thank you so much.
@Jan, Thank you for the help. I will now give it a try.

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by