How to use If elseif else in array ?

19 ビュー (過去 30 日間)
Ajaree Rattanaharn
Ajaree Rattanaharn 2019 年 2 月 6 日
コメント済み: YT 2019 年 2 月 7 日
I have variables of the image call 'IGray' in picture below
variables IGray.png
now I want to write the if elseif code to find amount of the value that I separate in 3 ways
  1. the value < 50
  2. the value 50-220
  3. the value > 220
primary, I try to write but it can not . As shown below
which I want ThW, ThWB and ThB show in the workspaces and it can double click to show all variables.
matt.png
Please help me TT
Thank you very much ^^
  3 件のコメント
Steven Lord
Steven Lord 2019 年 2 月 6 日
Do you want to display ThW in the Command Window once if any of the elements in Threshold_IGray is greater than or equal to 220, once if all the elements in Threshold_IGray is greater than or equal to 220, or a number of times equal to the number of elements in Threshold_IGray that are greater than or equal to 220? You're likely to get a different number of ThW's displayed in each of those three scenarios.
Ajaree Rattanaharn
Ajaree Rattanaharn 2019 年 2 月 7 日
Yess I try but I can't write the code

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

採用された回答

YT
YT 2019 年 2 月 6 日
So everytime I have to do somethings similar, I either do it by using a for-loop and if/else statement and comparing every field of the matrix (ii,jj) to the condition OR I use logical indexing. So I've provided both options to show you the difference in the amount of code and the execution time.
clear;
% dummy matrix
A = randi([0 255],1171,1591);
tic
ThB1 = 0;
ThBW1 = 0;
ThW1 = 0;
% with for-loop and if/else (I like this...)
for ii = 1:size(A,1)
for jj = 1:size(A,2)
if(A(ii,jj) <= 50)
ThB1 = ThB1 + 1;
elseif(((A(ii,jj) > 50) && (A(ii,jj) <= 220)))
ThBW1 = ThBW1 + 1;
else
ThW1 = ThW1 + 1;
end
end
end
toc
% Elapsed time is 0.055028 seconds.
tic
% alternative logical indexing (...but this is brilliant)
ThB2 = sum((A <= 50),'all');
ThBW2 = sum(((A > 50) & (A <= 220)),'all');
ThW2 = sum((A > 220),'all');
toc
% Elapsed time is 0.003860 seconds.
  3 件のコメント
Stephen23
Stephen23 2019 年 2 月 7 日
編集済み: Stephen23 2019 年 2 月 7 日
@Ajaree Rattanaharn: The vector dimension / 'all' option was added in R2018b:
For earlier versions you will have to either use (:), or used nested sum calls.
Note that you should always look at the documentation for your installed MATLAB version, which would have made it clear that it does not support this option.
YT
YT 2019 年 2 月 7 日
Like @Stephen Cobeldick suggested, instead of using 'all', you can try this instead
sum(sum(((A > 50) & (A <= 220)),1),2)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeScope Variables and Generate Names についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by