Simple if statement not working

4 views (last 30 days)
I am creating a script that allows a user to input a data file, and get an output data file out of it that includes mean, median, mode, variance, standard deviation, etc. The output file has to have a very specific format, but this format is not possible WHEN there is more than one mode. I just want to print a statement if there is more than one mode that acknowledges this, but my if statement is not working for some reason. Here is what I have:
U = unique(x(:));
H = histc(x(:),U);
x_mode_vertical = U(H==max(H));
%ensures all the modes are listed if there is more
%than one mode
x_mode = x_mode_vertical';
if size(x_mode) ~= [1 1]
fprintf('There is more than one mode, and as such, more than one mode will print with the output file.\n')
end
The first 3 lines creates a vertical array of every single mode, based on x. x is the data array that will be input by the user, and it is either one column or two columns of an unknown length. Using it as x(:) converts it all to one column so I am able to create descriptive statistics more easily. The next line creates my desired output variable, x_mode, by flipping x_mode_vertical, because I want x_mode to be a horizontal array.
The if statement is then where the script doesn't work. The script doesn't produce any error messages, it just acts as if it is ignoring those lines. Anyway, to check if there is more than one mode, I check the size of x_mode. If the size of x_mode isn't equal to [1 1], then there has to be more than one mode. For example, with the data file I am currently experimenting and testing with, there are four modes. So even after this script is done running, I will check with the command window:
>>size(x_mode)
And what is returned to me:
[1 4]
Which obviously isn't equal to [1 1]. Yet the script doesn't print the statement I want it to, and just passes over it.

Accepted Answer

Matthew Piccolo
Matthew Piccolo on 16 Apr 2017
I solved this on my own, here is what I did.
size_x_mode = size(x_mode);
if size_x_mode(2) ~= 1
fprintf('There is more than one mode, and as such, more than one mode will print with the output file.\n')
end
I created a new variable array and then wrote the if statement to check the second element of this array. If anyone could provide an explanation for why my first try at this didn't work, I would appreciate it.

More Answers (1)

Steven Lord
Steven Lord on 16 Apr 2017
When you type:
if size(x_mode) ~= [1 1]
the body of the if statement only gets executed if ALL the elements of the condition are true. Instead of testing like this, I recommend you use isscalar.

Categories

Find more on Preprocessing Data 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!