MATLAB without using loops, determine if the variance is above the threshold, returning a 1 or 0

38 Views Asked by At

I'm trying to write this program in MATLAB where, without using loops I need to take an array which has 3 rows, and an unknown number of columns.

We take this array, and find the variance of each of the columns. If that variance is grater than a threshold, then we set a the corresponding column in our output array to 1.

This is what I have so far:

% vec_acc_total is my array with 3 rows

var = var(vec_acc_total, 0, 1);

walking_segments_no_loops = zeros(size(var));
walking_segemnts_no_loops(var >= THRESHOLD) = 1

However something is wrong with this, hoping for any help, will be appreciated. I know it is wrong as after it is returned, It is put through a verification program (provided to me) which will confirm or deny.

There is also potentially an issue with my use of the VARIANCE function in MATLAB. I need to find the variance of each column.

I have tried the following:

walking_segments_no_loops = var >= THRESHOLD

Which also did not return the correct value

1

There are 1 best solutions below

0
Wolfie On

When you run

var = var(vec_acc_total, 0, 1);

You are overwriting the built-in function var with your variable var. All subsequent calls to var() (the function) will error until you clear var (the variable) from your workspace.

So run clear to clean things up and prevent any shadowing, then pick a new variable name, e.g.

v = var(vec_acc_total, 0, 1);

v is a 1xN array, where var_acc_total was a 3xN matrix, which tells us intuitively that the variance for each column has been calculated.

You can directly check whether this exceeds a threshold without initialising an array:

walking_segments_no_loops = (v >= THRESHOLD);

This outputs a logical array the same size as v, which is true (1) when greater than or equal to the threshold and false (0) otherwise. If you want this to be numerical instead of logical, you can convert it by wrapping with, for example, double().

Note in your question you say this (emphasis mine):

If that variance is greater than a threshold, then we set a the corresponding column in our output array to 1.

Maybe you want to use > instead of >= to check for a strict inequality.