Reputation: 431
I have measurement data from four sensors, each gives current speed at a given water depth (d) and time (t). Below is the matrix dimension of these four current measurements:
cs1 = [d1 x t1]; cs2 = [d2 x t2]; cs3 = [d3 x t3]; cs4 = [d4 x t4]
The water depth arraysd1, d2, d3, d4
are unique values, but their range overlaps. For example, d1=5:4:141
and d2=72:2:200
. Time arrays t1,t2,t3,t4
also have different start and end points with different timesteps.
I need to create a combined matrix cs
which includes data from all four sensors. For this I have created a NaN
matrix as:
t = unique([t1;t2;t3;t4]);
d = unique([d1 d2 d3 d4]);
cs = NaN(length(d),length(t));
% Populaitng data from 1st sensor
for i=1:length(d1)
for j=1:length(t1)
cs(d==d1(i) & t==t1(j))=cs1(i,j);
end
end
I am using a for
loop to populate the cs
matrix for one instrument data at a time. This way is quite inefficient since both depth and time array sizes are quite large.
Is there a quicker method to fill the cs
matrix without running a for
loop for each intrument?
Upvotes: 0
Views: 39
Reputation: 607
First we generate some sample input data. Note that this data is in a data structure that allows us to loop over the sensors, instead of writing separate code for each of the four sensors.
% sample input data
sensors = struct;
sensors.d = { ...
1:1:5; % d1
2:2:6; % d2
3:2:7; % d3
2:1:4; % d4
};
sensors.t = { ...
1:2:7; % t1
2:3:5; % t2
1:4:9; % t3
3:1:5; % t4
};
sensors.cs = { ...
1 * ones(length(sensors.d{1}), length(sensors.t{1})); % cs1
2 * ones(length(sensors.d{2}), length(sensors.t{2})); % cs2
3 * ones(length(sensors.d{3}), length(sensors.t{3})); % cs1
4 * ones(length(sensors.d{4}), length(sensors.t{4})); % cs2
};
Then we combine the sensor data into a single matrix. It's not clear from your example how you want to combine the data, so we will make the assumption that you want the combined matrix to start as all zeros and then add each sensor's data element-by-element.
% COMBINE SENSOR DATA INTO SINGLE MATRIX
% dimensions
d = unique(cat(2, sensors.d{:}));
t = unique(cat(2, sensors.t{:}));
% initialize matrix
cs = zeros(length(d), length(t));
% loop over sensors
for s = 1 : length(sensors.cs)
% indexes of sensor's d and t dimensions in combined d and t dimensions
[~, Id] = ismember(sensors.d{s}, d);
[~, It] = ismember(sensors.t{s}, t);
% add the values to the combined matrix
cs(Id, It) = cs(Id, It) + sensors.cs{s};
end
If instead you want to, for example, start from an all-NaN matrix and have each element represent the last sensor whose data is added, you can replace the line cs = zeros(length(d), length(t));
with cs = NaN(length(d), length(t));
and the line cs(Id, It) = cs(Id, It) + sensors.cs{s};
with cs(Id, It) = sensors.cs{s};
.
Upvotes: 1