JoeAverage
JoeAverage

Reputation: 23

How to convert logical conditions to a variable of a function

I would like to achieve the above for the following:

Rn = 0.009; % Resolution of simulation (in m^3)
Xs = -1 : Rn : 1;
Ys = -1 : Rn : 1;
Zs =  0 : Rn : 1; 

[X Y Z] = meshgrid(Xs, Ys, Zs); 
alpha   = atan2(Z,X);
ze      = x.^2 + y.^2; % define some condition
m       = 0.59; % manual input
cond    = (pi/3 <= alpha)     & ...
          (alpha <= (2*pi/3)) & ...
          (m <= Z)            & ...
          (Z <= ze); % more conditions 

xl = nnz(cond);        % the number of non-zero elements   
f  = abs(xl*1000 - 90) % guessing m to get f as low as possible

How do I turn m into a variable for some f function so I can call fminsearch to quickly find the corresponding m for f ≈ 0?

Upvotes: 1

Views: 62

Answers (1)

Richard
Richard

Reputation: 276

In order to use m as a variable, you need to define a function handle. So you need to write:

 cond = @(m) ((pi/3) <= alpha) & (alpha <= (2*pi/3)) & (m <= Z) & (Z <= ze);

However, you cannot use a function handle in the nnz routine, since it only accepts matrices as inputs. But, the solution to the problem is that you only have Boolean variables in cond. This means, you can simply sum over cond and get the same result as with nnz.

The only issue I see is how to implement the sum in fminsearch. Unfortunately, I do not have access to fminsearch, however I would assume that you can do something with reshape and then multiply with dot (i.e. .*) with the unity vector to get a sum. But you'll have to try that one out, not sure about it.

Upvotes: 1

Related Questions