how to use certain values to write a for loop?

조회 수: 17 (최근 30일)
Siddharth Parmar
Siddharth Parmar 2016년 2월 22일
댓글: Siddharth Parmar 2016년 2월 25일
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
Stephen23
Stephen23 2016년 2월 25일
편집: Stephen23 2016년 2월 25일
There is absolutely no point in using a slow and ugly loop. Here is Walter Roberson's much better solution in full:
>> X = [67;89;78;56;55;75;99];
>> f = [4;5];
>> X1 = X;
>> X1(f) = 5 * X1(f)
X1 =
67
89
78
280
275
75
99
Siddharth Parmar
Siddharth Parmar 2016년 2월 25일
I understand that it looks simple because I have modified my code and asked a simple question. Imagine if you have the array with 1000 rows in X and f. Then the loop simplifies it.

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

채택된 답변

Arnab Sen
Arnab Sen 2016년 2월 25일
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
Jos (10584)
Jos (10584) 2016년 2월 25일
Use the single command any(..) rather than the three commands ~empty(find(..))
any(f==i)
Siddharth Parmar
Siddharth Parmar 2016년 2월 25일
Thanks guys this is exactly what I was looking for.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 2월 25일
편집: Stephen23 2016년 2월 25일
ismember(i, f)
Or, you can use
X1 = X;
X1(f) = 5 * X(f);
with no loop.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by