replacing a value in all columns with value of tha

2019-07-15 09:04发布

问题:

How do I replace all the 1s in ALL columns with the number of that column? I can already do it column by column:

output(output(:,3)==1,3) = 3;
output(output(:,4)==1,4) = 4;
output(output(:,5)==1,5) = 5;
etc...

but I feel like a fool writing that out for every single column. There should be a way to do them all at once right?

回答1:

You can use FIND for this:

[rowIdx,colIdx] = find(output==1);
output(output==1) = colIdx;


回答2:

I don't quite get what you're trying to do, but you could use a MATLAB for loop.

for i=1:numberOfColumns,
    output(:,i) = i;
end

Is this sort of like you're after...?

Edit:

for x=1:numberOfRows,
    for y=1:numberOfColumns,
        if output(x, y) == 1
            output(x, y) == y
        end
    end
end

By the way I may have the columns/rows the wrong way round because I can't remember which way MATLAB represents its matricies!