how to find values and following values in a struct
Mostrar comentarios más antiguos
Hi! I have a struct Interval (attached), that cointained region's location_id, visited by a user in a different days (31) and in different intervals of time (12 intervals of 2 hours). I want to find in the struct for every day (31) if is present the value 21714; if it's present, I want to find the following values.
E.g. I find value 21714 in first row of Interval, so I want like output 21714 and the following values in the same row
a=[21714 1067829]
I find value 21714 in fourth row, interval_8, so I want like output 21714 and the following values in the same row
a =[21714 18417]
and so on for all the values 21714 in the struct.
I don't know how to do, can you help me? I hope the question is clear
1 comentario
Tim Wilko
el 9 de Jun. de 2016
Could you please clarify what you mean by each row? Do you want the next number after 21714 to be in the same interval or the same day?
For example, in the case of interval_8, is it the corresponding value in interval_9, or the next entry of interval_8 that you're after?
Thank you,
Tim
Respuesta aceptada
Más respuestas (1)
Sachin Shrestha
el 9 de Jun. de 2016
Hi Elisa,
Perhaps the following code could be another way to deal with the problem: Here, I have assumed, that the value 21714 doesn't exist in the last column. Next, in case of absence of non-empty column following the value, it will add zero instead. Also, for the array following the value, it will save the first element of the array.
load('matlab.mat');
structInterval = Interval;
fields=fieldnames(structInterval); % extract the name of the fields
dataCounter=1;
a=zeros(numel(structInterval),2); % to store the values
val2Check = 21714; % value that is to be checked
for i=1:numel(structInterval) % loop for 31 days to data
for j=1:length(fields) % loop for 12 intervals
valofStruct = structInterval(i).(fields{j}); % get value to be checked
if (valofStruct) % if value is non-empty
if valofStruct == val2Check % if value is the one, here 21714
for k=j+1:length(fields) % check for remaining data in the row, will generate error if the data is in the last row, need to add a condition
valofStruct_2 = structInterval(i).(fields{k});
if(valofStruct_2)
a(dataCounter,:)=[val2Check valofStruct_2(1)]; % keep the value 21714 and following data
dataCounter=dataCounter+1;
% -- do anything else you may want to
break;
elseif k==length(fields) % if empty data in the remaining rows, add zero
a(dataCounter,:)=[val2Check 0];
dataCounter=dataCounter+1;
% -- do anything else, you may want to
end
end
end
end
end
end
a=a(1:dataCounter-1,:); % extract only the non-empty data from 'a'
disp(a);
Hope this will be helpful. Good Luck!
Categorías
Más información sobre Numbers and Precision en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!