how to use certain values to write a for loop?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Siddharth Parmar
am 22 Feb. 2016
Kommentiert: Siddharth Parmar
am 25 Feb. 2016
X = [67;89;78;56;55;75;99];
f = [4;5];
for i = 1:length(X);
if i == f;
X1(i,1) = 5*X(i,1);
else
X1(i,1) = X(i,1);
end
end
I know that the way i have written the if expression is wrong but can someone tell how do I write the if expression such that it uses the values of f.. basically if i equals the value in the f matrix or array the first formula is used else the second.
Thanks for help.
Sid
2 Kommentare
Akzeptierte Antwort
Arnab Sen
am 25 Feb. 2016
Hi Siddharth,
My understanding from your problem statement that you want to check whether the values of the variable 'i' is present in the vector 'f' in the if-statement. You can use in-built 'find' function for this purpose. 'find' function returns the indices of the vector which meet certain condition. If no match then it returns a empty vector. So you can write the if statement in the following way:
>>if(~isempty(f==i))
So, the whole script as below:
if true
% code
end
X = [67;89;78;56;55;75;99];
f = [4;5];
for i = 1:length(X);
%if i == f
if(~isempty(find(f==i)))
X1(i,1) = 5*X(i,1);
else
X1(i,1) = 1*X(i,1);
end
end
For more detail about 'find', refer to the following link:
2 Kommentare
Jos (10584)
am 25 Feb. 2016
Use the single command any(..) rather than the three commands ~empty(find(..))
any(f==i)
Weitere Antworten (1)
Walter Roberson
am 25 Feb. 2016
Bearbeitet: Stephen23
am 25 Feb. 2016
ismember(i, f)
Or, you can use
X1 = X;
X1(f) = 5 * X(f);
with no loop.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!