I don't know how to use if function with or operator

3 vues (au cours des 30 derniers jours)
Tovai
Tovai le 17 Avr 2023
Modifié(e) : Stephen23 le 17 Avr 2023
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

Réponses (1)

Stephen23
Stephen23 le 17 Avr 2023
Modifié(e) : Stephen23 le 17 Avr 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
(following the rules of operator precedence) is exactly equivalent to this:
(((((((((((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.
  2 commentaires
Tovai
Tovai le 17 Avr 2023
Thank you so much for the fast reply! As a beginner I've learned so much from your code. You gave me exactly what I was looking for.
Stephen23
Stephen23 le 17 Avr 2023
Modifié(e) : Stephen23 le 17 Avr 2023
@Tovai: you can probably replace those loops with:
m = data(:,2:3);
x = ismember(data(:,1),[0,pow2(-4:5)])
m(:,~x) = 0

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by