Calling previous iterations values from an matrix
古いコメントを表示
when I run the code, "index exceeds matrix dimensions" error occurs. My aim is to find maximum row sum and when difference between max value of earlier iteration and current iteration are close (defined by tolerance) then iteration should stop. I am not able to locate error and yet thinking how to code.Can you please tell me the correct code.
for k=1:10 % Main iteration Loop
for i=1:5 % For matrix creation
for j=1:5
A(i,j)=rand % Matrix
end
end
b=zeros(1, 5)
for i=1:5
b=b+A(i,:) % Row sum
end
[b_max, index]=max(b) % find and fprintf of maximum row sum, find its row number and its elements
if b_max(i)-b_max(i-1)<=0.1 % is it a correct way to call previous iteration values
fprintf('iterations taken=%d',k)
fprintf('max value=%14.4f of row% with elements (x1,..,5)=%4.4f',b_max(iteration), index(iteration), A(k,:))
end
end
3 件のコメント
Joshua
2017 年 6 月 26 日
mukund,
Your error is caused because b_max only has one value in it and you are trying to access b_max(6). I took at stab at cleaning up your code a bit, but I still am a bit confused about what the second fprintf line is trying to accomplish. You never defined the variable iteration and I am not sure what your intent was with index(iteration) because to my knowledge index is not a MATLAB command.
Also, be careful when using this many for loops. If you have 'for i=1:10', i will only change values inside that for loop. After the loop is over, i will keep its last value of 10 for all subsequent calculations.
iteration=10;
for k=1:iteration % Main iteration Loop
for i=1:5 % For matrix creation
for j=1:5
A(i,j)=rand; % Matrix
end
end
b=sum(A);
b_max(k)=max(b); % find and fprintf of maximum row sum, find its row number and its elements
end
for m=1:length(b_max)
for n=1:length(b_max)
if abs(b_max(m)-b_max(n))<=10 % is it a correct way to call previous iteration values
fprintf('iterations taken=%d\n',k)
%fprintf('max value=%14.4f of row% with elements (x1,..,5)=%4.4f',b_max(iteration), index(iteration), A(k,:))
end
end
end
Let me know if that helps.
Joshua
2017 年 6 月 28 日
mukund,
Is this maybe what you are looking for? The loop now compares consecutive iterations to each other. Also, I added a third dimension to A so you could store A for each iteration. I still don't think the text output is quite what you want though.
iteration=10;
for k=1:iteration % Main iteration Loop
for i=1:5 % For matrix creation
for j=1:5
A(i,j,k)=rand; % Matrix
end
end
b=sum(A(:,:,k));
b_max(k)=max(b); % find and fprintf of maximum row sum, find its row number and its elements
end
for m=2:length(b_max)
if abs(b_max(m)-b_max(m-1))<=10
fprintf('iterations taken=%d\n',iteration)
fprintf('max value=%14.4f of row\n% with elements (x1,..,5)=%4.4f',b_max(m), m, A(:,:,m))
end
end
回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!