I don't know how to use if function with or operator
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have (data), a 14x3 array. The first column consists of numbers ranging from 0 to 48 but most of them are powers of 2 (...4,8,16...). These numbers represent the sizes of rocks. The two other columns represent the mass of the rocks in two samples. For example the row 8 464 1028 means that there was 464 grams in the 1st sample and 1028 grams in the 2nd sample of 8 mm rocks.
I'm making a logarithmic figure of this data and for my calculations the rock sizes that are not any power of 2 are useless for me. (I know this will result in errors but it's fine.)
I want my function to check if data(n,1) is on the power of 2. If it is, I want the function to save the data(n,2) (in case of the 1st sample) to m1(n), otherwise leave it as it is (a zero). What am I doing wrong???
TL;DR: I want to code: "if x = number1 or number2 or number3" but I can't get it working.
n=numel(data(:,1));
m1=zeros(1,n);
m2=zeros(1,n);
for i=1:n
if data(i,1)== 0||0.0625||0.125||0.25||0.5||1||2||4||8||16||32
m1(i)=data(i,2)
end
end
for k=1:n
if data(k,1)== 0||0.0625||0.125||0.25||0.5||1||2||4||8||16||32
m2(k)=data(k,3)
end
end
0 Commenti
Risposte (1)
Stephen23
il 17 Apr 2023
Modificato: Stephen23
il 17 Apr 2023
The simple MATLAB approach:
if any(data(i,1)==[0,0.0625,0.125,0.25,0.5,1,2,4,8,16,32])
or even simpler:
if any(data(i,1)==[0,pow2(-4:5)])
Note that MATLAB's logical operators have two inputs. So your code:
data(i,1)== 0||0.0625||0.125||0.25||0.5||1||2||4||8||16||32
(((((((((((data(i,1)== 0)||0.0625)||0.125)||0.25)||0.5)||1)||2)||4)||8)||16)||32)
which after the first comparison you are always comparing the logical output of the previous comparison against some non-zero value: logical||value. Because the values are non-zero, the result will be true. Not very useful.
The solution, as always, is to remember that MATLAB stands for "MATrix LABoratory", and that you need to think in terms of matrices and vectors... then you can write simpler, neater, efficient code that actually works.
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!