Problem using if statements in for loop
Mostra commenti meno recenti
I use these codes to generate a matrix inside the for loop:
kd=zeros(1,7);
kd=[0.11:0.01:0.17];
for ii=1:length(kd)
for j=1:7
kp(j)=j;
ki(j)=j;
AA(ii,j)=ki(j);
end
end
Result:
AA =
1 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7
Then I put if statements inside the for loop to change the elements of the matrix AA. Interestingly, the result is as follows:
kd=zeros(1,7);
kd=[0.11:0.01:0.17];
for ii=1:length(kd)
for j=1:7
kp(j)=j;
ki(j)=j;
if kd(ii) == 0.11
ki(j)=100;
elseif kd(ii) == 0.12
ki(j)=200;
elseif kd(ii) == 0.13
ki(j)=300;
elseif kd(ii) == 0.14
ki(j)=400;
elseif kd(ii) == 0.15
ki(j)=500;
elseif kd(ii) == 0.16
ki(j)=600;
elseif kd(ii)==0.17
ki(j)=700;
end
AA(ii,j)=ki(j);
end
end
Result:
AA =
100 100 100 100 100 100 100
200 200 200 200 200 200 200
300 300 300 300 300 300 300
400 400 400 400 400 400 400
1 2 3 4 5 6 7
600 600 600 600 600 600 600
700 700 700 700 700 700 700
How can I solve this problem?
2 Commenti
kd=zeros(1,7);
kd=[0.11:0.01:0.17];
for ii=1:length(kd)
for j=1:7
kp(j)=j;
ki(j)=j;
AA(ii,j)=ki(j);
end
end
The above can be just achieved with:
kd = repmat(1:7,7,1)
Serdar Ethem Hamamci
il 10 Feb 2022
Risposte (1)
Welcome to the world of numerical maths. See: FAQ: Why is 0.3-0.2-0.1 not equal to zero?
The standard example is:
any((0:0.1:1) == 0.3) % FALSE!!!
Most floating point numbers cannot be represented exactly in the binary format, they are stored in in the IEEE754 standard. This is the format used in Matlab and on all modern CPUs.
This means, that the IF command is working as expected, but kd(ii) == 0.15 is not suitable:
format long g
kd = 0.11:0.01:0.17;
kd.' - 0.15
Do you see it?
By the way, [ ] is the concatenation operator in Matlab. In [0.11:0.01:0.17] you concatenate the vector 0.11:0.01:0.17 with nothing, so this is just a waste of time.
2 Commenti
Serdar Ethem Hamamci
il 10 Feb 2022
Jan
il 11 Feb 2022
Some simplifications:
% kd = zeros(1,7); % Omit this, because it is a waster of time
% You define kd but overwrite it in the following line.
% kd = [0.11:0.01:0.17];
kd = 0.11:0.01:0.17; % As explained already:
% a:b:c is a vector already. There is no need to concatenate it with
% nothing.
AA = zeros(length(kd), 7); % Pre-allocation!!!
for ii = 1:length(kd)
% for j=1:7 % No need to do this repeatedly
% kp(j)=j; Omit this
% ki(j)=j; Omit this
if abs(kd(ii)-0.11)<0.001
ki=100; % No need to use (j) as index
elseif abs(kd(ii)-0.12)<0.001
ki=200;
elseif abs(kd(ii)-0.13)<0.001
ki=300;
elseif abs(kd(ii)-0.14)<0.001
ki=400;
elseif abs(kd(ii)-0.15)<0.001
ki=500;
elseif abs(kd(ii)-0.16)<0.001
ki=600;
elseif abs(kd(ii)-0.17)<0.001
ki=700;
end
AA(ii, :) = ki; % Set the complete row to ki
% end
end
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!