필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

matrix operation by element of other matrix

조회 수: 2 (최근 30일)
Offroad Jeep
Offroad Jeep 2015년 4월 7일
마감: MATLAB Answer Bot 2021년 8월 20일
Hi All, Hope all going fine...... I need your help please....... THANKS IN ADVANCE FOR TAKING OUT TIME..............
Consider A = 3 X 3 matrix. then I want to generate N number of random values. take first value and add to the matrix. if the value reduces accept and replace the element of A with that new value otherwise keep the value.
EXAMPLE : for understanding of helpers A = 2 -3 7 RANDOM NUMBERS= -1 3 -2 -1 TAKE FIRST RANDOM NUMBER THAT IS -1, ADD TO A A_NEW = 1 -4 6 NOW I WANT TO KEEP 1 AND 6 BECAUSE THE COME CLOSER TO 0 BUT -4 HAS GONE FAR FROM ZERO SO REJECT IT AND GIVE OUTPUT AS A = 1 -3 6
NOW TAKE THE NEXT RANDOM NUMBER DO THE SAME PROCEDURE NOW A_NEW BECOMES = 4 0 9 REJECT 4 AND 9 AND MAKE A AS A = 1 0 6
NOW TAKE NEXT RANDOM NO BUT DON'T OPERATE ON 0 VALUES THAT IS NEXT RANDOM NO IS -2 SO A_NEW WILL BE -1 0 4 . IMPORTANT 1 HAS CROSSED ZERO AND BECAME -1 SO DONT CHANGE IT AND KEEP A = -1 0 4
IN EASY WORDS GENERATE A MATRIX N x N WITH + AND - VALUES .... TAKE RANDOM NUMBERS IN + AND -, .... OPERATE THEM IF THE ELEMENT APPROACHES 0 CHANGE IT WITH NEW ONE AND IF NOT RETAIN THE PREVIOUS VALUE. ULTIMATELY AFTER SEVERAL NUMBER OF MONTE CARLO STEPS THE ENTIRE MATRIX MOST OF THE VALUES WILL BE NEAR TO ZERO.............
I have tried the following code but want to stop it when values reach between -0.5 and 0.5
clc
clear all
format compact
a = randi(6,3,3)-3
a = a(:)
nmc = 50
da(1:nmc)=((rand(1,nmc))-0.5)
for i = 1:nmc
a_trial = a + da(i)
if a_trial < a
a(:,:) = a_trial
elseif a_trial > a
a_trial = a(:,:)
end
end

답변 (1개)

James Tursa
James Tursa 2015년 4월 7일
편집: James Tursa 2015년 4월 7일
for i = 1:nmc
a_trial = a + da(i);
x = abs(a_trial) < abs(a); % Find all indexes where a_trial is closer to 0
a(x) = a_trial(x); % Replace elements of a with elements of a_trial closer to 0
if( max(abs(a)) <= 0.5 ) % If all elements are between -0.5 and +0.5
break;
end
end

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by