How to find minimum value from loop using if function iteration?

I have a=6.5, I would like to define "if function" inside the "for loop", for i=1:10, it will do the loop imin < a < imax, and if the "if function" is correct, I would like to use the b= imin (in which the a function is correct).
My expectation toward the code is b=6. Since the 6.5 is in between number for loop 6 and 7. And I want to use 6 (imin where the a is in correct statemen for if function)
How do I code that in matlab?
a=6.5;
for i=1:10
imin=i;
imax=imin+1
if imin<a<imax
b=imin;
end
if imax==10;
end
end

2 个评论

Hi Stephen,
Thank you for the answer. But, how if in the case of hundred thousand. I can not use floor() function for it. Otherwise, I still need to use if function inside for loop, if it is possible?
For example:
From below code, I expect to have b value in 135, since a is between 135000 and 136000. and b=imin/dx=135.
a=135500;
dx=1000;
for i=1:10
imin=i*dx;
imax=imin+dx
if imin<a<imax
b=imin/dx;
end
if imax==10;
end
end

请先登录,再进行评论。

 采纳的回答

>> a = 135500;
>> dx = 1000;
>> b = floor(a/dx)
b = 135

4 个评论

Anom Sulardi's "Answer" moved here:
Hi Stephen,
Thanks again for your kind help. In some cases, I can use that code actually.
So, this is my actual code now.
I expect to have result KK=3 since z0 is in between the hh(3)=9.5 and hh(4)=16. That's why I prefer to use if function inside for looping.
hh=[1.5, 5, 9.5, 16, 25, 37.5, 57.5, 95, 160, 250, 400, 600, 850, 1250, 2250];
z0=11.5;
for k=1:15 % I have 15 layer of hh
if hh(k)<=z0<hh(k+1)
KK=k % please do find KK= minimum k where statement is true
end
end
>> hh = [1.5, 5, 9.5, 16, 25, 37.5, 57.5, 95, 160, 250, 400, 600, 850, 1250, 2250];
>> z0 = 11.5;
>> KK = find(hh<=z0,1,'last')
KK = 3
Hi Stephen,
Thank you so much. That's really help me a lot.
However, I have another problem. How can I indexing 4-D array matrix by using 2-d or 3-d array?
Let say, I want to index the 4-D matrix A with the A(3,5,7,10) and A(4,6,8,10). However, the first, second, and third array on indexing is exist inside the matrix a,b,c. Can matlab do this?
I try to use diag(C), but it doesn't work well.
A=rand(10,10,10,10);
a=[3;4];b=[5,6];c=[7,8];
C=A(a,b,c,10);
Use sub2ind:
A = rand(10,10,10,10);
a = [3,4];
b = [5,6];
c = [7,8];
X = sub2ind(size(A),a,b,c,[10,10]);
C = A(X)

请先登录,再进行评论。

更多回答(1 个)

Instead of using imin<a<imax, try using an intersection of two commands for checking less than and greater than seperatly.

a=6.5;
for i=1:10
    imin=i;
    imax=imin+1
    if (imin<a)&&(a<imax)
        b=imin;
    end
    if imax==10;
    end
end

This will give the output as 6

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by