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