hi
so i know there are many efieciant ways to do things on matlab without the need to use the if statement, and I was wondering if someone could help out on converting this excel formula/code to matlab without the need for a double if statements
=IF(AND(E5=0,E4<>0),F4+1,F4)

 채택된 답변

Monika Jaskolka
Monika Jaskolka 2021년 7월 30일
편집: Monika Jaskolka 2021년 7월 30일

0 개 추천

I don't see that a "double if" is necessary:
x = 0;
if (~E5 && E4)
x = F4 + 1;
else
x = F4;
end
If you are asking for a one line conditional assignment like below, Matlab doesn't support this syntax
condition ? true-expression : false-expression

댓글 수: 6

Engineer Undergoing
Engineer Undergoing 2021년 7월 30일
but will it apply for the rest of elements in the vector and not just the fourth in Vecrtor F and the fifth element in vector E?
  • If you are asking for a one line conditional assignment like below, Matlab doesn't support this syntax
Sometimes you can write down if condition in one line
x = (~E5 && E4) + F4;
Monika Jaskolka
Monika Jaskolka 2021년 7월 30일
편집: Monika Jaskolka 2021년 7월 30일
@Engineer Undergoing No. You didn't mention anything about vectors E and F in your question. Please provide the Matlab definitions of E and F. Please also better describe what you actually want to accomplish. Where are you storing the result? I assumed there was some variable x to store the result. Is that a vector also? What do the indices mean? Is E5 is the current value, or the next value?
Engineer Undergoing
Engineer Undergoing 2021년 7월 30일
yeah I failed to mention there are two vectors, first vector is E( 450x1) and the second is F( 450x1), and it's storing (rewriting) it in the F vector. it starts from the first cell or indice and keeps on adding when the condition is true until the end of the matrix aka by 450th cell, so basically it's a point count. I included a snapchot for better ilusteration to what I mean.
Below is a direct translation, but if you are simply counting non-zero elements in E, you should look into the nnz command for a simpler solution.
% Init data
E = zeros(19,1);
E(15) = -0.333333;
E(16) = 0.333333;
F = ones(19,1);
F(17:end) = 2;
for i = 1:length(E)-1
if ~E(i+1) && E(i)
F(i) = F(i) + 1;
end
end
Rik
Rik 2021년 8월 2일
@Monika Jaskolka Consider teaching yourself to use numel instead of length. It is never a worse option, and it might save you from a difficult bug hiding in your program due to array input (instead of vector inputs).

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2021년 7월 30일

댓글:

Rik
2021년 8월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by