For-loop, inserting loopcount into string output
Afficher commentaires plus anciens
Hello,
I've been tasked with a project which partly consists of having to load data from a file and displaying it in a (X,3) matrix. The challenging part is that there are requirements for the values for every coloumn of the matrix, such as; the numbers in coloumn 1 cannot be lower than 20, nor higher than 60.
If a value of given coloumn does not meet the criteria, the respective set of data is to be eliminated and removed from the end result matrix. I've managed to do just that without any major problems, although I am not stating that my code is as simple as possible. Here is the problem, however; for every time that a given value does not meet the respective requirement, the code is supposed to provide a string output describing exactly which value it is. Since I've tested my code where multiple values in different coloumns should display the error message, I simply do not know how to make the code display the exact position of the specific value.
In the end it simply displays the three error strings, one after the other. I was thinking that i could add the value "i" in the strings of my if-statements in my for-loop, causing the string to display which position the value has in the matrix, for example:
disp('Error; explanation, [value (i)]'), or something alike. I just dont know the syntax.
I'd love to get some help! Thank you in advance.
if true
% code
end
function data = dataLoad(filename)
Q = readtable(filename);
A1 = zeros(length(Q),1); A2 = zeros(length(Q),1); A3 = zeros(length(Q),1);
Temperature = Q(:,1);
GrowthRate = Q(:,2);
Bacteria = Q(:,3);
i = 1;
for i = 1 : length(Q)
if (Temperature(i)>=20) && (Temperature(i)<=60)
A1(i) = A1(i) + Temperature(i);
end
if (GrowthRate(i)>=0)
A2(i) = A2(i) + GrowthRate(i);
end
if (Bacteria(i)>=1) && (Bacteria(i)<=4)
A3(i) = A3(i) + Bacteria(i);
end
if (Temperature(i)<20)
A1(i) = 0; A2(i) = 0; A3(i) = 0;
disp('Error; explanation');
elseif (Temperature(i)>60)
A1(i) = 0; A2(i) = 0; A3(i) = 0;
disp('Error; explanation');
end
if (GrowthRate(i)<0)
A1(i) = 0; A2(i) = 0; A3(i) = 0;
disp('Error; explanation');
end
if (Bacteria(i)<1)
A1(i) = 0; A2(i) = 0; A3(i) = 0;
disp('Error; explanation');
elseif (Bacteria(i)>4)
A1(i) = 0; A2(i) = 0; A3(i) = 0;
disp('Error; explanation');
end
i = i + 1;
end
A1 = A1(A1~=0); A2 = A2(A2~=0); A3 = A3(A3~=0);
data = [A1, A2, A3];
1 commentaire
Dennis
le 11 Juin 2018
You can use strcat to put several strings together and num2str to convert i or A(i) to a string.
errorstring=strcat('Error;',{' '},num2str(A(i)),' <20!');
disp(errorstring)
Réponse acceptée
Plus de réponses (1)
ES
le 11 Juin 2018
disp(['Error in row ', num2str(i)]);
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!