indices when the columns are all nan

I am using [m, d] = nanmax (r_all); to get the maximum values and corresponding indices in matlab. There are several columns in r_all in which all the elements are nans. Unfortunately, nanmax returns '1' in indices for those columns that have all nans. However, there are actual indices that are value '1' so it creates confusion. How can I force matlab to return 'a' or 'b' as the output instead of returning 0' or '1'? Could you please suggest other solutions to this problem?

6 Comments

sweep the matrix with 2 for loops and apply the nanmax or an if (r_all(i,j)==NaN) to set output to a value you know no other r_all element has.
Then you can do whatever you want
Thanks! could you please elaborate what do you mean by sweep the matrix?
KSSV
KSSV on 16 Mar 2016
Edited: KSSV on 16 Mar 2016
sweep in the sense run a for loop for each element of column and row.
Sagar
Sagar on 16 Mar 2016
Edited: Sagar on 16 Mar 2016
But how can I apply for loop within [m d], I cannot do m(i,j) or d(i,j) right? I can set the nan values with any other values in the matrix r_all, but the problem remains the same, i.e. nanmax still returns 1 for the maximum index in d because all the values in many columns are nans.
you attach your matrix.....
Sagar
Sagar on 16 Mar 2016
Edited: Sagar on 16 Mar 2016
attached is the data. Please follow the link: https://drive.google.com/file/d/0B67659k3uth9Nks5OTUzZ2JRYU0/view?usp=sharing

Sign in to comment.

 Accepted Answer

Stephen23
Stephen23 on 16 Mar 2016
Edited: Stephen23 on 16 Mar 2016
There is no need to waste time using slow and ugly loops and if statements. You can locate those "incorrect" indices very simply using basic MATLAB indexing:
>> mat = [0,1,2,NaN,3,NaN;4,NaN,5,NaN,6,NaN;7,8,NaN,NaN,NaN,9]
mat =
0 1 2 NaN 3 NaN
4 NaN 5 NaN 6 NaN
7 8 NaN NaN NaN 9
>> [m,idx] = nanmax(mat) % max value and its indices
m =
7 8 5 NaN 6 9
idx =
3 3 2 1 2 3
>> idx(all(isnan(mat),1)) = NaN % replace all-NaN indices with NaN
idx =
3 3 2 NaN 2 3

3 Comments

+1, loops and branches are completely unnecessary
A slightly simpler implementation would be:
[m, idx] = nanmax(mat);
idx(isnan(m)) = nan;
By the way, since 2015b (iirc) max ignores nan by default.
Sagar
Sagar on 17 Mar 2016
Edited: Sagar on 17 Mar 2016
Great, I like Guillaume's answer. :)
Thanks Stephen, apparently I didn't know there is 'all' function which I needed. :)

Sign in to comment.

More Answers (1)

clc; clear all ;
load data.mat ;
[m,n] = size(data) ;
idx = zeros(n,1) ;
val = idx ;
% column wise
for c = 1:n
[i,j] = nanmax(data(:,c)) ;
if isnan(i)
j = 50 ;
end
idx(c) = j ;
val(c) = i ;
end

Products

Asked:

on 16 Mar 2016

Commented:

on 17 Mar 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!