필터 지우기
필터 지우기

What is the best way to define vectors based on a condition?

조회 수: 4 (최근 30일)
Christian Berwanger
Christian Berwanger 2021년 7월 28일
댓글: KSSV 2021년 7월 28일
Hello,
So I do have a function, which has the (same sized) vectors x,y,z as input parameters and a same sized k as an output parameter.
Now I want to calculate k with a simple for loop. As I come from other languages I could get it to run. However it is pretty slow and I know MATLAB has a lot of tricks for these kind of stuff.
So the minimal running example code is:
A=2.*p+1;
Bm=p+1;
Bs=p+2;
x_i=(x+y)*0.01;
x_s=x-x_i;
[r,c] = size(T);
k = zeros(r,c);
for i=1:r
if x(i)>=x_i(i)
k(i)=A(i)+Bm(i).*x_s(i);
elseif x(i)<x_i(i)
k(i) = A(i)+Bs(i).*x_s(i);
end
if k(i)==0
k(i) = 0.001;
end
end
Does MATLAB have a more efficient way to implement this?
Thanks in advance

답변 (1개)

KSSV
KSSV 2021년 7월 28일
편집: KSSV 2021년 7월 28일
A=2.*p+1;
Bm=p+1;
Bs=p+2;
x_i=(x+y)*0.01;
x_s=x-x_i;
[r,c] = size(T);
k = 0.001*ones(r,1);
% condition 1
idx1 = x>=x_i ;
k(idx1)=A(idx1)+Bm(idx1).*x_s(idx1);
% condition 2
idx2 = x<x_i ;
k(idx2) = A(idx2)+Bs(idx2).*x_s(idx2);
  댓글 수: 6
Christian Berwanger
Christian Berwanger 2021년 7월 28일
Yes. I know. But if, for some reason (which rarely might occur (As A,Bm and Bs are defined in a different way. However it would too complex for just a minimal working example), within the condition, k will be 0, I want to catch it. I just want to be sure as I later divide by k.
KSSV
KSSV 2021년 7월 28일
Okay, then you may go ahead with that.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by