# Matlab: how to write column number to new column if boolean condition is met

I have a sample matrix similar to this one in matlab (although my real matrix contains many more columns)

``````List = [0,0,1;1,0,0;0,1,0;0,1,0;0,0,0]

List =

0     0     1
1     0     0
0     1     0
0     1     0
0     0     0
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

What I am trying to find is a way that I could sum conditions that are TRUE (= 1) into a new variable with only one column, but that indicates the column number in a structure like the following list

``````ListNew =

3
1
2
2
0
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

Is there a function or easy way to do this in Matlab?

+3

source to share

3 answers

There is an easier way: `find()`

``````[ListNew,~] = find(List');
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

Taking into account the comment below, it can be changed as follows:

``````ListNew=zeros(5,1);
[Col,Row] = find(List');
ListNew(Rows)=Col;
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+4

source

If your matrix is ​​just `0`

and `1`

, and you only have one `1`

in each row, you can do this,

``````List = List .* repmat(1:size(List,2),size(List,1),1);
sum(List,2)
ans =
3
1
2
2
3
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+3

source

One-layer solution with `sum`

, `cumsum`

and `fliplr`

-

``````out = sum(cumsum(fliplr(List),2),2)
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

Another c approach `max`

for a two line solution -

``````[idx,valid] = max(List,[],2)
out = idx.*valid
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+1

source

All Articles