1
votes

I have matrix something like A=[NAN 0.9 0.8 0.7; NAN NAN 0.7 0; NAN NAN NAN NAN] and

I want to tell MATLAB that-

For all columns in A- If column contains only NAN then return the index of last NAN element, else find the maximum value from each column and return the value and index.

Thus, ultimately I will have vectors like- value vector = 0.9,0.7,NA and index vector = 2, 3, 4 for this particular example. and

I think I can try "if else" loop inside the for loop but I don't know how to do it. Can anyone help?

Thanks in advance.

2

2 Answers

4
votes

You can do this fairly easily using max:

A = [NaN 0.9 0.8 0.7; NaN NaN 0.7 0; NaN NaN NaN NaN];
[max_val,max_ind] = max(A,[],2);
max_ind(isnan(max_val)) = size(A,2);

The second output of max is the index of the maximum value. By default it will ignore NaN values, unless every value is NaN, in which case it returns 1. The 3rd line of this snippet simply finds values where the maximum value is NaN (i.e. the whole row is NaN), and replaces the index with the length of the row.

0
votes

Here is simple, brute-force method. I applaud the finesse of MrAzzaman.

for j = 1:size(A,2)
    if sum(isnan(A(:,j))) == size(A,1)
        valueVec(j) = NaN;
        indexVec(j) = size(A,1);
    else
        [valueVec(j),indexVec(j)] = max(A(:,j));
    end
end