How to make a Comparison of the values of a matrix for different iteration ?

조회 수: 1 (최근 30일)
If I have a matrix A of any size (mXn) , And i want to iterate it maybe for the 100 times .So how I can do the comparision of the i and i+1 number of iteration value for the specific column number and stop my Program to do iteration if i get the better solution in my i+1 number of iteration and show the result .
A=randi([2 5],[3,4])
j=10
B=cell(j,1)
for i=1:j
B{i}=A.*randi([2 5] ,[3,4])
end
here By this code code i am getting 10 different B matrix values .But i want to do comparision between two different iteration .If my previous iteration value is higher than the next one then it will only display the previous one .and it will stop the execution of program .

채택된 답변

Image Analyst
Image Analyst 2022년 5월 12일
I know you've already accepted a solution that must work for you but I thought I'd offer a different solution:
A=randi([2 5],[3,4])
maxIterations = 100
[rows, columns] = size(A)
% Set up output for B
B = zeros(rows, columns, maxIterations);
% Do loop
columnToInspect = 2;
for k = 1 : maxIterations
B(:, :, k) = A .* randi([2, 5], [3, 4]);
% Do some sort of comparison,
% like if the mean of col 2 of B is 30% more than what it
% was on the previous iteration, break.
if k > 1
thisMean = mean(B(:, columnToInspect, k));
priorMean = mean(B(:, columnToInspect, k-1));
if thisMean > 1.3 * priorMean
fprintf('Breaking at iteration %d.\n', k)
% Display previous iteration
B(:, :, k-1)
break;
end
end
end

추가 답변 (1개)

Chunru
Chunru 2022년 5월 11일
편집: Chunru 2022년 5월 11일
A=randi([2 5],[3,4])
j=10
for i=1:j
B=A.*randi([2 5] ,[3,4]);
% Do your comparison here between B and A
% Now assign B to A
A = B;
end
  댓글 수: 2
Akash Pal
Akash Pal 2022년 5월 11일
but here how to assign the iteration number ,my program will be in loop so i need to do the comparision between maybe ith and (i+1)th iteration . there is my confusion
Chunru
Chunru 2022년 5월 11일
The process of iteration looks like this:
Initialization: A
iter 1: Calculate B based on A; Compare the result now (B) with the previous result (A); A=B
iter 2: Calculate B based on A (which is the result of the previous iteration) and so on
....

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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by