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)

 采纳的回答

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 个评论

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;
@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?
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
@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 中查找有关 Data Import from MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by