## 'How to' Matrix

Asked by Hello kity

### Hello kity (view profile)

on 12 Dec 2012

I have an array with 0 s and 1s.

Example a colomn, 0 ,0 ,0 ,0 , 1.

Now the 1 is on the 5th row, I want to raise that to the first row.

So, in my code i want all the ones to go 4 steps up...

sounds easy, but how :) ?

Jan Simon

### Jan Simon (view profile)

on 12 Dec 2012

@Student: The question remains, what "raise to the first row" exactly means. At first I guess it is the "first column", but "raising" can be swapping, shifting, circular shifting, sorting, cropping or any procedure I cannot imagine currently.

Hello kity

### Hello kity (view profile)

on 12 Dec 2012

I meant shifting, shifting the 1 on the 4th row to the 1st.

Jan Simon

### Jan Simon (view profile)

on 12 Dec 2012

Thanks for the clarification, Student. And what happens on the right margin? Is the result shorter, filled with zeros or ones or with the value of the last element?

## Products

No products are associated with this question.

### Walter Roberson (view profile)

Answer by Walter Roberson

### Walter Roberson (view profile)

on 12 Dec 2012
Edited by Walter Roberson

### Walter Roberson (view profile)

on 12 Dec 2012

Have you considered circshift() up by 4 rows?

### Azzi Abdelmalek (view profile)

Answer by Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 12 Dec 2012

```A=[0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1]
for k=5:length(A)
if A(k)
b=A(k-4:k-1);
A(k-4)=1
A(k-4+1:k)=b
end
end
```

Hello kity

### Hello kity (view profile)

on 12 Dec 2012

Would you comment this code step by step, I dont get how you do this...

thank you

Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 12 Dec 2012
``` A=[0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1]
for k=5:length(A)
if A(k)            % If A(k) is equal to 1
b=A(k-4:k-1);  % store value from k-4 to k-1 in b
A(k-4)=1       % replace value at k-1 by 1
A(k-4+1:k)=b   % shift value stored in b
end
end```

### Andrei Bobrov (view profile)

Answer by Andrei Bobrov

### Andrei Bobrov (view profile)

on 12 Dec 2012
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 12 Dec 2012

other way:

a - your vector - row (eg: [0 0 0 0 1])

```n = numel(a);
out = a(hankel(1:n,[n,1:n-1]));
```

or

```out = hankel(a,circshift(a,[0 1]));
```

Hello kity

### Hello kity (view profile)

on 12 Dec 2012

thank you,

afterwards i use Q=out(:,5);

### Jan Simon (view profile)

Answer by Jan Simon

### Jan Simon (view profile)

on 12 Dec 2012
Edited by Jan Simon

### Jan Simon (view profile)

on 12 Dec 2012

Some ideas:

```x = [0, 0, 0, 0, 1];
index = find(x, 1, 'first');
y1 = x(index:end);
y2 = [x(index:end), zeros(1, index - 1)];
y3 = [x(index:end), ones(1, index - 1)];
y4 = [x(index:end), repmat(x(end), 1, index - 1)];
y5 = [x(index:end), x(1:index - 1)];
```

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi