简体   繁体   中英

Replacing Repeated Values in Each Row of a Matrix with NaN

I am trying to create a function that would replace repeated values in each row of a matrix with NaNs. My code works except that I can't seem to get it to apply to every row. It applies the code to each row, but will only accept "n" as the number of columns, not the number of rows, so if there are more rows than columns then it won't do every row. For example, if I have 8 rows and 6 columns it will only let me put in 6 for n, not 8. Yet it applies the code to the rows but only the first 6 rows. Here is a working example:

X = [1 2 3 4 4 4; 1 2 3 4 5 5; 1 2 2 2 2 2; 1 2 3 3 3 3; 
1 1 1 1 1 1; 1 2 3 4 4 4; 1 2 3 3 3 3; 1 2 2 2 2 2];

n=6
nanfill = nan(1,n);
for i=1:n
    temp = [unique(X(i,:)), nanfill];
    X(i,:) = temp(1:n);
end

It gives me this for my original matrix:

1 2 3 4 4 4
1 2 3 4 5 5
1 2 2 2 2 2
1 2 3 3 3 3
1 1 1 1 1 1
1 2 3 4 4 4
1 2 3 3 3 3
1 2 2 2 2 2

Then this is the output I get for the new matrix after running my code:

1   2   3   NaN NaN NaN
1   2   3   4   NaN NaN
1   2   NaN NaN NaN NaN
1   2   3   NaN NaN NaN
1   NaN NaN NaN NaN NaN
1   2   3   4   NaN NaN
1   2   3   3   3   3
1   2   2   2   2   2

If I attempt to put in the number of rows, 8, for "n" then it gives me the following error:

Unable to perform assignment because the size of the left side is 1-by-6 and the size
of the right side is 1-by-8.

That is because your matrix's rows have elements in them. You can't assign a vector that is 8 elements long into a shorter one. Better would be to check the length of the rows so that they will definitely match:

X = [1 2 3 4 4 4; 1 2 3 4 5 5; 1 2 2 2 2 2; 1 2 3 3 3 3; 
1 1 1 1 1 1; 1 2 3 4 4 4; 1 2 3 3 3 3; 1 2 2 2 2 2];
n=size(X,2) % <- # of columns (length of one row)
nanfill = nan(1,n);
for i=1:n
    temp = [unique(X(i,:)), nanfill];
    X(i,:) = temp(1:n);
end

If the values in each row are always non-decreasing, as in your example, you can use the following. It computes the difference between each entry and the one to its left, and writes NaN if that difference is zero:

X([false(size(x,1),1) ~diff(X,[],2)]) = NaN;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM