필터 지우기
필터 지우기

Generate a matrix with alternative positive and negative values with ones

조회 수: 14 (최근 30일)
Hello, Any idea how to generate a matrix with ones with positive and negative values. For example
We know,
A=ones(n,1)=[1;1;1;1], if n=4
I would like a matrix like this:
A=[1;-1;1;-1]
However, n will change of size depending on the processed data.
On the other hand, I would like to generate a matrix with the following form
if n=10
A=[1;0.5;0;-0.5;-1;-.5;0;0.5;1;0.5], the n value can change depending on the uploaded data.
Thank you.

채택된 답변

John D'Errico
John D'Errico 2023년 7월 21일
편집: John D'Errico 2023년 7월 21일
Learn to use various tools in MATLAB. In this case, mod will help you. Forexample:
n = 4;
mod(1:n,2)
ans = 1×4
1 0 1 0
Does that get you close to what you want? You want a column. But that is easy. And you want +/-1. Also easy.
mod((1:n)',2)*2 - 1
ans = 4×1
1 -1 1 -1
Simple enough. Again, look for your target, and think of what you can do to get there.
As for the second case, it is not clear what general pattern you expect in there. If n was larger, would the step still be 0.5? Would this be a periodic function? Or a simple V-shape?
  댓글 수: 2
Jorge Luis Paredes Estacio
Jorge Luis Paredes Estacio 2023년 7월 21일
Thank you very much, concering to your question. It could be like a random signal (interms of amplitudes), not necesarily a V shape.
John D'Errico
John D'Errico 2023년 7월 21일
편집: John D'Errico 2023년 7월 21일
A v-shape is most simply achieved using abs. Again, look for something that gets you close to your target. For example:
n = 9;
abs((1:n) - (n+1)/2)
ans = 1×9
4 3 2 1 0 1 2 3 4
Now we can scale those numbers. and put in a shift.
abs((1:n) - (n+1)/2)/2
ans = 1×9
2.0000 1.5000 1.0000 0.5000 0 0.5000 1.0000 1.5000 2.0000
V = abs((1:n) - (n+1)/2)/2 - 1
V = 1×9
1.0000 0.5000 0 -0.5000 -1.0000 -0.5000 0 0.5000 1.0000
plot(V,'-o')

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Dyuman Joshi
Dyuman Joshi 2023년 7월 21일
n = 10;
vec = (0:n-1)';
%Array A
A = cospi(vec)
A = 10×1
1 -1 1 -1 1 -1 1 -1 1 -1
%Array B
vec0 = vec+4;
B = 4*abs(vec0/8-floor(vec0/8+0.5))-1
B = 10×1
1.0000 0.5000 0 -0.5000 -1.0000 -0.5000 0 0.5000 1.0000 0.5000

Steven Lord
Steven Lord 2023년 7월 21일
Another approach:
r = 4;
c = 5;
A = (-1).^((1:r).' + (1:c))
A = 4×5
1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by