Effacer les filtres
Effacer les filtres

How to use AND in an if loop to find the first repeated value

2 vues (au cours des 30 derniers jours)
mcl1993
mcl1993 le 23 Août 2016
Réponse apportée : Robert le 23 Août 2016
I have a list of values and want to go through a csv file to find if any of the numbers in column 3 match any of the values in the list. If they do, i want to find the first time this value occurs (there are likely to be more than one matches to the list) and add together the value in column 6, the first time it occurs, to the value in column 6 in the next row.
for i = 1:length(value(:,3));
for j = 1:length(allowed_energies);
if value(i,3) == allowed_energies(j) AND if it is the first time it occurs;
value(i,6) + value(i+1,6);
end
end
end

Réponse acceptée

Adam
Adam le 23 Août 2016
for j = 1:length( allowed_energies )
idx = find( value(:,3) == allowed_energies(j), 1 );
result = value( idx, 6 ) + value( idx + 1, 6 );
end
would do this, I think, although depending what you actually want to do with the result of adding those columns together you would want to alter it a bit. In your example code you just add them together and throw the result away. Which is also what I do above, but I give it a name first and then throw it away at least!
You may also be able to vectorize further to remove the remaining loop too, but I don't have the time to consider that one further.

Plus de réponses (1)

Robert
Robert le 23 Août 2016
You can accomplish this with intersect. To illustrate, let's make an example file:
mydata = randi(9,[100,6]);
myfile = 'temp.csv';
csvwrite(myfile,mydata);
Then we can read it back in (if it is very big, you might want something faster than csvread) and compare its third column to the list of values using intersect. The first output will show us which values were and weren't found and the second gives us the indices of mydata at which they occur first.
myvalues = [1,3,5,6,8];
mydata = csvread(myfile);
[valuesfound,ii] = intersect(mydata(:,3),myvalues);
Then we want to add the data in the sixth column and in the rows we just found to the data in the following rows (still sixth column). If one of the rows we found is the last row, we don't have a next row to use. It is up to you what you should do in such a case, but here I append a row of zeros before doing the addition.
mydata(end+1,6) = 0; % in case ii includes last row
output = mydata(ii,6)+mydata(ii+1,6);

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by