Save variable in vector form after a loop
조회 수: 1 (최근 30일)
이전 댓글 표시
here is y code for calculating norm between two vectors and then saving the minimum number and its index in variable r and c, i want to save these two generated after completing the loop, what i am facing a problem is that when i use the the save command it save only the last iteration but i need the whole thing. please help me in my work.
clc; clear all;
filename1 = 'my_file.mat'; %500x1
r2 = load(filename1);
r1 = xlsread('my_excel file','sheet1'); %1060 rows
for i = 1:size(r1,1)
for j = 1:500
T = norm(r2.C(j,:)-r1(i,5:end));
RS(ss) = T;
ss = ss + 1;
end
[r,c]=min(RS);
ABC=fprintf('%5.5f\t %d\n',r,c);
end
댓글 수: 0
채택된 답변
Geoff Hayes
2015년 3월 29일
Muahmmad - if you want to save the r and c from each iteration, then you must create an array/vector for each and save the values for the ith iteration into these new arrays. For example, you know that iterate from 1 to size(r1,1), so initialize your r and c to be arrays of this size
rArray = zeros(size(r1,1),1);
cArray = zeros(size(r1,1),1);
for i = 1:size(r1,1)
for j = 1:500
% etc.
end
[rArray(i) cArray(i)] = min(RS);
ABC=fprintf('%5.5f\t %d\n',rArray(i),cArray(i));
end
Note how on each iteration we save the result of min to the arrays rArray and cArray. Now when you use the save command, use rArray and cArray which has all data from each iteration.
As an aside, consider using indexing variables other than i and j since MATLAB uses these to represent the imaginary number.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!