Conditional function on matrix

Hello,
This is a tough one to explain.
I am analysing a big chunk of data and now I have a equation defined by intervals.
Kd=1 for Kt<0.2
Kd=e for 0.2<=Kt<=1.09*c2
Kd=f for Kt>1.09*c2
Kt=rand(8784,89);
c2=ones(size(Kt))/2;
e=rand(size(Kt));
f=rand(size(Kt));
I've simplified it quite a bit, because it envolves other matrixes (all with the same size (8784,89)) on the conditions.
My question is, how to execute it? I've tried piecewise, but I'm stuck with the symbolic. I would need to get Kd as double.
Kd(Kt)=piecewise(Kt<0.2,1, 0.2<=Kt<=1.09*c2,10, Kt>1.09*c2,5);
I've tried with If and elseif but as far as I've seen it will only analyze the first element of the array to verify if the condition is true:
if Kt<0.2
Kd=1;
elseif 0.2<=Kt<=1.09*c2
Kd=e;
elseif Kt>1.09*c2
Kd=f;
end
Other ideas or something I'm missing?
edit: edited after trying solution given by Matt J.
thanks.

 采纳的回答

Matt J
Matt J 2019-4-23
编辑:Matt J 2019-4-23
vals=[1,10,5];
Kd=vals( discretize(Kt,[-inf,0.2,1.09*c2,+inf]) );

5 个评论

Did you try that solution? I cannot run it, I get an error.
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
Error in test (line 8)
Kd=vals(discretize(Kt,[-inf,0.2,1.09*c2,+inf]));
Sorry, I didn't notice that c2 was non-scalar. In that case, I would just use simple logical indexing.
Kd=ones(size(Kt));
thresh=1.09*c2;
Kd(Kt>=0.2 & Kt<=thresh)=10;
Kd(Kt>thresh)=5;
No worries, I was trying to figure it out and decided to ask if you did try just to check if there was something I was not seeing.
Thank you, it works. But I see now that I didn't gave the best example because I set the answers as a value when in fact I have arrays.
Kd=1 for Kt<0.2
Kd=10 for 0.2<=Kt<=1.09*c2 ->this one should be Kd=e for 0.2<=Kt<=1.09*c2
Kd=5 for Kt>1.09*c2 -> this one should be Kd=f for Kt>1.09*c2. Where:
e=rand(size(Kt));
f=rand(size(Kt)); *
Once I change the ouctomes to arrays in case of true condition I get a new problem: In an assignment A(:) = B, the number of elements in A and B must be the same.
I've tried to change all to same sized arrays, just to check but I'm still missing something.
*I've editted this in the 1st post.
Kd=ones(size(Kt));
condition1 = Kt>=0.2 & Kt<=1.09*c2;
condition2 = Kt>1.09*c2;
Kd(condition1)=e(condition1);
Kd(condition2)=f(condition2);
See also,
Thanks Matt! I was reading a bit further into logical indexing. Thanks for the link also!

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by