How to reshape 1-D to 2-D matrix with missing data?
4 views (last 30 days)
Show older comments
I need to reshape a 1-D array into a 2-D matrix. The difficulty is that there is random missing data so the RESHAPE function cannot be used in the typical fashion.
I have a set of 3 arrays: x-coordinates, y-coordinates, and a scalar.
For example, this is my input:
x = [ 1 1 1 1 1 2 2 3 3 3 ]
y = [ 1 2 3 4 5 1 2 1 2 5 ]
c = [ 2 1 2 1 2 1 2 1 2 1 ]
and this is my desired output:
x = [ 1 1 1 1 1 ; 2 2 2 2 2 ; 3 3 3 3 3 ]
y = [ 1 2 3 4 5 ; 1 2 3 4 5 ; 1 2 3 4 5 ]
c = [ 2 1 2 1 2 ; 1 2 NaN NaN NaN ; 1 2 NaN NaN 1 ]
Help is much appreciated.
2 Comments
dpb
on 12 Aug 2014
In general something like this is tough as one presumes the location of missing values is also more or less random. For any give in case it's pretty much trivial; generically to discover the pattern of the missing values is likely more difficult.
In your case above, one can presume from the output that the first row is complete -- is that a fair assumption in general, however?
Accepted Answer
More Answers (1)
Joseph Cheng
on 12 Aug 2014
Edited: Joseph Cheng
on 12 Aug 2014
Well you could do something like this.
x = [ 1 1 1 1 1 2 2 3 3 3 ]
y = [ 1 2 3 4 5 1 2 1 2 5 ]
c = [ 2 1 2 1 2 1 2 1 2 1 ]
X = [min(x):max(x)]'; %since x is rows you know you have a maximum of X rows.
X = repmat(X,1,max(y)); %then make it a block based on maximum y value.
Y = [min(y):max(y)];
Y = repmat(Y,max(x),1);
C = nan*zeros(max(x),max(y));
for ind = 1:length(c)
C(x(ind),y(ind))=c(ind);
end
where by building the X and Y based on the knowledge of the structure and a C full of NaNs. Then use the x and y positioning to know which row and column to put the corresponding c value. You may be able to get away from the for loop but forgot how to get C(x,y)=c type of syntax to work out. Something isn't clicking on why that wouldn't work out. (I know matlab is doing the permutations between x and y not x(1) and y(1) then x(2) and y(2) as i'm doing in the for loop.) forgot how to accomplish that without doing a for loop.
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!