Dear all, how can I solve the index exceed the number of array problem?

1 view (last 30 days)
Index exceeds the number of array elements (0).
water_level_time1 = Waterlevel_P1(:,1);
water_density = 1000;
weather_pressure = [];
for i=1:size(Waterlevel_P1,1)
index = find(water_level_time1(i) == weather_time);
if size(index, 1) > 0
weather_pressure(i, 1) = Pressure(index(1));
else
previous_elements = find(weather_time < water_level_time1(i));
next_element = find(weather_time > water_level_time1(i));
weather_pressure(i, 1) = (Pressure(previous_elements(end)) + Pressure(next_element(1)))/2;
end
end
  2 Comments
Sindar
Sindar on 16 Oct 2020
use code blocks (see toolstrip) and copy the full error text when asking questions
Caroline Ganglo
Caroline Ganglo on 17 Oct 2020
Thanks for your comment,
here is the loop created, and the error.
water_level_time1 = Waterlevel_P1(:,1);
water_density = 1000;
weather_pressure = [];
for i=1:size(Waterlevel_P1,1)
index = find(water_level_time1(i) == weather_Time);
if size(index, 1) > 0
weather_pressure(i, 1) = Pressure(index(1));
else
previous_elements = find(weather_Time < water_level_time1(i));
next_element = find(weather_Time > water_level_time1(i));
weather_pressure(i, 1) = (Pressure(previous_elements(end)) + Pressure(next_element(1)))/2;
end
end
Here is the error
Index exceeds the number of array elements (0).
Error in Water_level_combined_data_151020 (line 62)
weather_pressure(i, 1) = (Pressure(previous_elements(end)) + Pressure(next_element(1)))/2;

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 17 Oct 2020
When the water level time is larger than anything in the array then the next element list would be empty and index 1 of it would be out of range.
By the way, have you considered using interp1 with extrapolation turned on?
  4 Comments
Caroline Ganglo
Caroline Ganglo on 17 Oct 2020
The water level time is at 15 mins interval while the weather time is at 1 min. In this case can I still use the code or what is the best option?
Walter Roberson
Walter Roberson on 17 Oct 2020
Best option for that kind of situation is probably converting the data into a timetable() and using retime()

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!