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

2 views (last 30 days)
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 .

Accepted Answer

Image Analyst
Image Analyst on 12 May 2022
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

More Answers (1)

Chunru
Chunru on 11 May 2022
Edited: Chunru on 11 May 2022
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 Comments
Akash Pal
Akash Pal on 11 May 2022
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 on 11 May 2022
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
....

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!