1
votes

I have a Nx3-matrix in matlab, where I have a degree value from 0 to 360 in the first column, a radius value from 0 to 0.5 in the second and an integer in the third. Every combination out of (M(n,1),M(n,2)) is unique with M the matrix and n a random number between 1 and N, but it is possible that there is a value in M(:,1) or M(:,2) more than once. M is sorted, first after the first row, then after the second.

My target is now to reshape this matrix into a 360xV-matrix, with V the amount of unique values in M(:,2). If there is a value in M(:,3) at the position M(o,1) and M(p,2) with 1 <= o, p <= N, it should be placed at the position (o,p), if there is no value, then there should a NaN-value placed instead.

Is there a simple way to do this, or do I have to write my own function for that?

Edit:
Desired input:

0 0.25 1  
0 0.43 4  
1 0.25 2  
2 0.03 5  
2 0.43 2 

Desired output:

NaN 1 4  
NaN 2 NaN  
5 NaN 2
2
Post a small example with input and desired outputLuis Mendo
@LuisMendo: Done, I hope this makes things a bit easier.arc_lupus

2 Answers

2
votes

You can use an approach of finding unique indices for the first and second columns from the input arrays and then using those to set elements in an appropriately (discussed in more detail inside the code as comments) sized output array with the elements from the third column. Here's the implementation -

%// Input array
A = [
    0 0.25 1
    0 0.43 4
    1 0.25 2
    2 0.03 5
    2 0.43 2 ]

%// Find unique indices for col-1,2
[~,~,idx1] = unique(A(:,1)) %// these would form the row indices of output
[~,~,idx2] = unique(A(:,2)) %// these would form the col indices of output

%// Decide the size of output array based on the "extents" of those indices
nrows = max(idx1)
ncols = max(idx2)

%// Initialize output array with NaNs
out = NaN(nrows,ncols)

%// Set the elements in output indexed by those indices to values from
%// col-3 of input array
out((idx2-1)*nrows + idx1) = A(:,3)

Code run -

out =
   NaN     1     4
   NaN     2   NaN
     5   NaN     2
-1
votes

Is there a simple way to do this, or do I have to write my own function for that?

You'll need to write a method, seeing that what you've described is utterly specific to your problem. There's methods to find unique values, so this will help you when designing your for loop.