Writing IF STATEMENT that omits empty fields in different arrays of a structure

I need writing an if statement that would exclude empty fields in a structured array (pictured attached). I am to make use of non-empty fields of M.id, M.xd and M.yd. I came up with this but not working:
for i=1:1:n % n is 100
if ~isempty M(i) % this is where my problem lies
for z=1:t % t is 5
min_dis_local=inf;
distanceL=sqrt( (S(i).xd-(M(z).xd) )^2
end
end
end
I got this error instead:
Error using isempty
Not enough input arguments.

Answers (1)

You need to use () with isempty, otherwise it would assume the input to be a string array
y = [];
isempty(y)
ans = logical
1
isempty y
ans = logical
0
%even though x is not defined, it returns 0 when checked with isempty
isempty x
ans = logical
0
When you add ~ operator before isempty without (), it will through you an error, which is what you encountered
~isempty y

5 Comments

I have enclosed the M(i) in a bracket as you corrected, it worked only to some extent, but brought up another error before completing the iteration:
Index exceeds the number of array elements (169).
for i=1:1:n % n is 100
if ~isempty(M(i)) % I have enclosed it in a bracket as you corrected
for z=1:t % t is 5
min_dis_local=inf;
distanceL=sqrt(S(i).xd-(M(z).xd) )^2
end
end
end
Please copy paste the full error message.
What is S? And what is the use of min_dis_local?
It would be better you provide all the code that is relevant to your issue.
This is a simple demo of the code
xm=1000;
ym=1000;
n=200;
S(n+1).xd=200;
S(n+1).yd=400;
for i=1:1:n
S(i).xd=rand(1,1)*xm;
XR(i)=S(i).xd;
S(i).yd=rand(1,1)*ym;
YR(i)=S(i).yd;
S(i).id=i;
end
Wmin=30;
for i=1:1:n
theta_m(i)=atan(abs(S(i+1).yd-S(i).yd))/S(i+1).xd-(S(i).xd);
S(i).theta_m=theta_m(i);
if (0 <= abs(theta_m(i))) && (abs(theta_m(i)) <= 360)
S(i).Wm=Wmin/theta_m(i);
if ~isempty(S(i).Wm)
S(i).type='M';
end
end
end
tau=sum(arrayfun(@(S) ~isempty(S.Wm),S));
for i=1:1:n
if S(i).type=='M'
if ~isempty(S(i))
M(i).xd=S(i).xd;
M(i).yd=S(i).yd;
M(i).id=S(i).id;
end
end
end
for i=1:1:n
if ~isempty(M(i)) % to calculate for only the nonempty fields in struct M
for z=1:tau
min_local=inf;
distanceL=sqrt( (S(i).xd-(M(z).xd) )^2 + (S(i).yd-(M(z).yd) )^2 );
if distanceL < min_local
min_local=distanceL;
end
S(i).d_distance=min_local;
end
end
end
What is the full error you get when you run this code?
Index exceeds the number of array elements (127)
Error in Demo_code (line 54) if ~isempty(M(i))

Sign in to comment.

Categories

Products

Release

R2021a

Asked:

on 25 Jan 2023

Commented:

on 29 Jan 2023

Community Treasure Hunt

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

Start Hunting!