Save variable in vector form after a loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Muhammad Usman
le 29 Mar 2015
Commenté : Muhammad Usman
le 29 Mar 2015
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 commentaires
Réponse acceptée
Geoff Hayes
le 29 Mar 2015
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!