Simple rounding numbers in a matrix

조회 수: 3 (최근 30일)
André Pacheco
André Pacheco 2012년 12월 21일
Hello,
I have a matrix that consist in a bunch of numbers. Por exemple matrix(a)=
1.46101448605678 0.124416958027372
0.00918754579219433 -0.0655659591723838
0.549665183459168 0.218046503150596
What i want to do is make something that can round my numbers to 0, -1 and 1. If the number in the matrix is <-0,5 it should put -1 if it is bigger than 0.5 it should put 1. And the other numbers put into 0.
Thanks in advance.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 21일
편집: Azzi Abdelmalek 2012년 12월 21일
A=2*rand(5)-1 % Example
A(A<-0.5)=-1;
A(A>0.5)=1;
A(-0.5<A & A<0.5)=0
  댓글 수: 2
André Pacheco
André Pacheco 2012년 12월 21일
It works, but it changes the structure of my matrix. Don't know why. My matrix is a 2x5 and after that it changes to a 1x10. Do you know why?
André Pacheco
André Pacheco 2012년 12월 21일
Oh, i solved this initiating the new matrix with zeros.

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

추가 답변 (3개)

Roger Stafford
Roger Stafford 2012년 12월 21일
편집: Roger Stafford 2012년 12월 21일
b = (a>.5)-(a<-.5);
Roger Stafford

Image Analyst
Image Analyst 2012년 12월 21일
Andre, if you have the Image Processing Toolbox, you can quantize your array with the imquantize function in a single line of code:
m=[...
1.46101448605678 0.124416958027372
0.00918754579219433 -0.0655659591723838
0.549665183459168 0.218046503150596]
m_quantized = imquantize(m, [-0.5, 0.5])-2
In the command window:
m =
1.46101448605678 0.124416958027372
0.00918754579219433 -0.0655659591723838
0.549665183459168 0.218046503150596
m_quantized =
1 0
0 0
1 0

Shaun VanWeelden
Shaun VanWeelden 2012년 12월 22일
편집: Shaun VanWeelden 2012년 12월 22일
Not to assume anything, but as a tutor for MATLAB, I have seen this question many, many times. If you are starting out in MATLAB, a good and easy approach is to use for loops and an if-else statement
[rows columns]=size(yourMatrix)
for i=1:rows
for j=1:columns
if yourMatrix(i,j)>.5
yourMatrix(i,j)=1
elseif yourMatrix(i,j)<-.5
yourMatrix(i,j)=-1
else %its between those two
yourMatrix(i,j)=0
end
end
end
I hope that helps you and anyone else, let me know if you have more questions :)
  댓글 수: 1
Image Analyst
Image Analyst 2012년 12월 22일
Do your students then tend to use this loop based approach even after they've been shown the vectorized approach? Or do they switch over immediately once they learn the vectorized approach after this? I've seen people use loops for matrices that are millions of elements, even though they've been using MATLAB for months or years, when they could have used a faster vectorized approach instead.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by