Reputation: 121
I have data like this: [...
0...0...0...0
6...0...0...0
8...5...2...0
9...8...3...1
0...0...0...0
Within each row I would like to subtract every value individually from every other in that row. So that I get a new matrix which shows all the differences like this: [...
null
0
3...6...3
1...6...8...5...7...2
null
I hope you see what I mean. I don't want to subtract 0 from anything (O is null for me-if you have a way to replace 0 with null thats fine). Or at least, if this has to be done, I want those results to be discarded. But I DO want there to be some placeholder when a row is entirely made of 0s.
The ordering of the resulting subtractions doesn't matter, except that the row order overall should be maintained.
Upvotes: 1
Views: 2042
Reputation: 74940
You can use PDIST to calculate the distances:
data =[0 0 0 0
6 0 0 0
8 5 2 0
9 8 3 1
0 0 0 0];
nRows = size(data,1);
%# for speed, preassign 'out'
out = cell(nRows,1);
for r = 1:nRows
pts = data(r,data(r,:)>0); %# this assumes valid entries are >0
switch length(pts),
case 0,
out{r} = []; %# empty for 'null'
case 1,
out{r}=0; %# zero if only one valid number
otherwise
out{r}=pdist(pts'); %'# calculate all differences
end
end
%# You access elements of a cell array with curly brackets
>> out{3}
ans =
3 6 3
Upvotes: 2