MATLAB matrix range assignment

2019-09-08 17:20发布

问题:

Is it possible to assign ranges to a matrix. If you consider the below zeros matrix as a 'grid' for plotting:

R = zeros(5,8);
R =
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

So can you treat this matrix as a grid so each x-axis zero can considered as a range? for example R(5,1) is a range 0-0.1 seconds. R(5,2) is a range 0.1-0.2 seconds etc.

Can the range idea also be applied to the columns?

The purpose for this is so I can read cell array data I have already organised into ranges into the zeros matrix to produce a 2d histogram.

回答1:

Assume you have the times tt and the datavalues val, where val(i) contains the datavalue for time tt(i). In your example you would have

tt  = [0.02, 0.22, 0.15, 0.08, 0.27, 0.09];
val = [0.5,  1.4,  2.5,  0.6 , 0.8,  0.3 ];

Now you need vectors that represent the time and data ranges that you want (increasing), for example

trange   = [0, 0.1, 0.2, 0.3, Inf];
valrange = [0, 1,   2,   3,   Inf];

Now you create a matrix of the right size

R = zeros(length(valrange), length(trange));

You can fill the matrix up easily just by looping over all times you have

for i=1:length(tt)
   %// We consider the pair tt(i), val(i)
   %// First find out, in which time range tt(i) lies:
   tind = find(trange > tt(i), 1, 'first');

   %// Now find out, in which value range val(i) lies:
   valind = find(valrange > val(i), 1, 'first');

   %// Now we increase the corresponding matrix entry
   R(valind,tind) = R(valind,tind) + 1;
end

Note that the first column corresponds to the time range between -Inf to trange(1) and the last column to the range between trange(end-1) and trange(end)==Inf. Simliary for the first and last row.



回答2:

I'm not sure if I understand your question.

If you ask, whether it is possible to assign a vector, e.g. a = [1;2;3], to be a column in some matrix R = zeros(3, 5), then this can be achieved by

R(:, 1) = a;
R(:, 2) = [4;5;6];