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

采纳的回答

Geoff Hayes
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by