Hello, is there any way I can define a matrix NxN whose elements are different real numbers between 0 and 5?
이전 댓글 표시
Hello, is there any way I can define a matrix NxN whose elements are different real numbers between 0 and 5?
답변 (4개)
Azzi Abdelmalek
2013년 10월 13일
N=5
out=reshape(linspace(0,5,N*N),N,N)
댓글 수: 2
jimaras
2013년 10월 13일
Azzi Abdelmalek
2013년 10월 13일
편집: Azzi Abdelmalek
2013년 10월 13일
M=rand(N)*5
M(randi(N*N))=0
M(randi(N*N))=5
Image Analyst
2013년 10월 13일
In your comments, you specified both 0 and 1 as the lowest value, so I made it flexible enough to handle either one:
N = 10; % Whatever you want
lowestValue = 1; % or 0 - whichever you want.
highestValue = 5;
theMatrix = lowestValue + (highestValue - lowestValue) * rand(N)
% Zero out first and last rows.
theMatrix(1,:) = 0;
theMatrix(end,:) = 0;
% Zero out first and last columns.
theMatrix(:,1) = 0;
theMatrix(:,end) = 0;
댓글 수: 4
jimaras
2013년 10월 13일
Image Analyst
2013년 10월 13일
Correct. Or zero, or any other number. The chance of getting any particular number EXACTLY is vanishingly small. For example, you'll most likely never hit 4.8 or 2.4 or 1.3 exactly either. If you're interested in integers, then use randi() instead of rand(). What exactly are you using this for anyway? Is it important that you get exactly 5 sometimes? If so, you're going to have to quantize your results, like round to the nearest 0.1 or something.
jimaras
2013년 10월 13일
Image Analyst
2013년 10월 13일
편집: Image Analyst
2013년 10월 13일
Like I said in the code, just change lowestValue:
lowestValue = 0;
What about the requirement that the outer edges of the array be zero? Recall where you said "the columns 1 and 2002 and the rows 1 and 2002 to be 0 " - to me, that means that column 1 and column 2002 (or the last column if N is different that 2002) should equal exactly 0. And the same for the first and last row - they are all zero. Again, is this still required? If not, just don't do the zeroing out and do:
N = 2002; % Whatever you want
lowestValue = 0; % or 1 - whichever you want.
highestValue = 5;
theMatrix = lowestValue + (highestValue - lowestValue) * rand(N)
Essentially (in an inflexible, hard coded manner):
theMatrix = 5 * rand(2002)
Did you follow what I said in my prior comment about never being able to hit any particular number exactly ?
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!