Info
この質問は閉じられています。 編集または回答するには再度開いてください。
fixing the values in matrix when it come between 0 and 1
1 回表示 (過去 30 日間)
古いコメントを表示
Hi all,I want to fix the values in matrix which comes between 0 and 1 and the other values carry on till the time when all the values are between 0 and 1. when all the values are between 0 and 1 the program should break.
a = randi(5,5)
nmc = 1000
for i = 1:nmc
b = rand(1)
c = a - b
if c < a
a = c
if (a > 0) && (a < 1)
break;
end
end
end
3 件のコメント
回答 (2 件)
Image Analyst
2015 年 9 月 10 日
編集済み: Walter Roberson
2015 年 9 月 10 日
I think you're trying to do this:
% Generate random numbers between 1 and 5.
a = randi(5,5)
nmc = 10000
for i = 1 : nmc
b = rand(1);
c = a - b; % c is a 5x5 matrix.
lessThanA = c < a;
% If c is less than a (which it will be),
% replace a with c. a will be smaller.
a(lessThanA) = c(lessThanA);
if all(a(:)>0 & a(:)<1)
break;
end
end
a
but I never got it to meet the condition for breaking.
2 件のコメント
Image Analyst
2015 年 9 月 11 日
That's because I did exactly what you asked for, which is not what you really want. I think Hamoon's latest solution, where b is some fraction of a, is probably what you want. If it is, please officially "Accept" his solution.
Hamoon
2015 年 9 月 10 日
編集済み: Hamoon
2015 年 9 月 10 日
Thank you image Analyst, I just changed the code a little bit, I think this is what 4*4 wants:
a = randi(5,5);
while true
condition = a>=0 & a<=1;
b = rand(1);
c = a - b; % c is a 5x5 matrix.
lessThanA = c < a;
% If c is less than a and condition isn't met,
% replace a with c. a will be smaller.
indexes = lessThanA & ~condition;
a(indexes) = c(indexes);
if all(condition)
break;
end
end
a
5 件のコメント
Hamoon
2015 年 9 月 11 日
It's OK, I got the problem here, the point is that "b" should NOT be a simple random value, you'd better calculate "b" based on magnetic field alignment formulation, but if you want to simply use random numbers for "b", you should consider that "b" is dependent to "a", in other words the amount that you subtract from "a" to force it to be aligned according to magnetic field, is dependent to "a". Here, i'm considering "a" shows the differences between orientation of a magnetic domain and an external magnetic field direction applied to that domain. So here, if a=0 then "b" should be zero.So "b" cannot be a simple random number. considering this fact, I just changed "b" a little bit and here is the code:
a = randi(5,5);
while true
b = rand(1)*a;
a = a - b;
if all(a>0 & a<1)
break;
end
end
a
here "b" is a random matrix, but it is dependent to "a", actually "b" is a random proportion of "a". I implemented the dependency of b to a using b=rand*a you may want to do something else, but it's all about "b", you don't need to change anything else.
here I also didn't define "c" variable, we don't need that.
この質問は閉じられています。
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!