- 1 < abc. This is either TRUE or FALSE, which is interpreted as 1 or 0
- 1 <= 5 or 0 <= 5. This is TRUE in both cases.
Hi Everyone, I need your help on my problem.
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a 3D matrix (abc), and I need to do if and elseif conditions to this matrix. However, the only the first expression(aa=abc-5) is applied to all elements. %
%
ab=[10,2,2;4,12,6;7,5,9];
abc=repmat(ab,1,1,3);
if 1<abc<=5
aa=abc-5;
elseif 6<abc<=10
aa=abc+10;
end
How can I make the elseif expression work?
Thank you.
Chane
댓글 수: 0
채택된 답변
Jan
2018년 3월 7일
편집: Jan
2018년 3월 7일
1 < abc <= 5
This will not do, what you expect. Matlab processes this expression from left to right:
You want:
1 < abc && abc <= 5
Then your if and elseif will work.
For productive code using logical indexing as suggested by Birdman is usually more efficient and nicer. But understanding why a<b<c fails is essential.
댓글 수: 3
Jan
2018년 3월 7일
If your Hx20_50 is a vector, you cannot use && but need &. But then the condition of the if command is a vector also. Because if requires a scalar condition, a all() is inserted automatically. This is most likely not, what you want.
Either use a loop:
t20_50 = zeros(size(Hx20_50)); % Pre-allocate!
for k = 1:numel(Hx20_50)
if 0<Hx20_50(k) && Hx20_50(k)<=0.5
t20_50(k) = sqrt(log(1 ./ (Hx20_50(k) .^ 2)));
elseif 0.5<Hx20_50(k) && Hx20_50(k)<=1
t20_50(k) = sqrt(log(1 ./ (1-Hx20_50(k)) .^ 2));
end
end
추가 답변 (1개)
Birdman
2018년 3월 7일
편집: Birdman
2018년 3월 7일
Actually, you do not need a ifelse statement. Simple logical indexing will give you what you want.
ab=[10,2,2;4,12,6;7,5,9];
abc=repmat(ab,1,1,3);
abc(abc>1 & abc<=5)=abc(abc>1 & abc<=5)-5;
abc(abc>6 & abc<=10)=abc(abc>6 & abc<=10)+10
댓글 수: 6
Walter Roberson
2018년 3월 7일
If the inputs are certain to be in that range then you can simplify to
mask = Hx20_50 <= 0.5;
t20_50(mask) = sqrt(log(1./(Hx20_50(mask).^2)));
t20_50(~mask) = sqrt(log(1./(1-Hx20_50(~mask)).^2));
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!