Creating values to a matrix with "if" statement

조회 수: 18 (최근 30일)
Ivan Mich
Ivan Mich 2019년 11월 6일
답변: Steven Lord 2019년 11월 6일
Hello,
I have a .csv file which includes two columns and each column has matrix 68x1.
in order to read the file I use these commands :
clc
clear
filename1= 'myfile.csv'
[d1,tex]= xlsread(filename1);
b=d1(:,1);
I would like to take some values using the sommand "if"
I have written :
if b>=4.5&&b<60
X=2*b+5
elseif b>=60
X=3*b-6
end
but it's no use. Could anyone help me please?
  댓글 수: 2
Ruger28
Ruger28 2019년 11월 6일
if b<=4.5 && b<60
all values of b <= 4.5 are also <60. What is your logic here?
Ivan Mich
Ivan Mich 2019년 11월 6일
Excuse me , its b>=4.5 && b<60

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

채택된 답변

Ruger28
Ruger28 2019년 11월 6일
편집: Ruger28 2019년 11월 6일
filename1= 'myfile.csv'
[d1,tex]= xlsread(filename1);
b = d1(:,1);
cntr = 1; % for values outside of range since no else statement
for ii = 1:length(b)
if b(ii) >= 4.5 && b(ii) < 60
X(cntr)=2 * b(ii) + 5;
cntr = cntr + 1;
elseif b(ii) >= 60
X(cntr)=3 * b(ii) - 6;
cntr = cntr + 1;
end
end
Since your data might not fit all of the if statements, a counter of sorts is needed (at least that is how I would do it with your example).
You were not indexing the "b" vector at all. You need to loop through all of the variables in the vector, compare them in the if, and store them away if the current value meets your logic requirements with the counter (cntr).
Edit: forgot to index the "b" in the elseif

추가 답변 (1개)

Steven Lord
Steven Lord 2019년 11월 6일
When you call if with a non-scalar expression as its condition, " An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric)." So this if statement will only execute its body if all elements of b are in the range [4.5, 60). [Actually, if b is non-scalar this should have thrown an error.]
if b>=4.5&&b<60
You could use a for loop as Ruger28 did or you could use logical indexing.

카테고리

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