Clear Filters
Clear Filters

HOW to Overwrite Matrix Values in a loop, not Append!! ??

2 views (last 30 days)
Hi guys! Hope you are doing great!
Well I run this particular code with the 4 matrices out_M, out_M_corr, out_R and out_R_corr.
(I have attached an EXCEL file - 'sample.xlsx' to show these matrices).
out_M_corr = out_M;
out_R_corr = out_R;
out_M_corr(:,3) = out_M_corr(:,3)*2; %these are the correction factors.....
out_M_corr(:,5) = out_M_corr(:,5)*5.3346;
for nR=1:size(out_R,1)
test = (out_M_corr(:,1) == out_R_corr(nR));
val = find(test,1,'first');
out_M_corr(test, 2) = out_M_corr(test, 2) - out_M_corr(val,2);
X(test,1) = out_M_corr(test,2);
Y(test,1) = out_M_corr(test,3);
poly = polyfit(X,Y,1);
out_R_corr(nR,4) = poly(1,1);
out_R_corr(nR,3) = poly(1,2);
end
The problem I am facing is in the loop. I want the matrices X & Y to always store new values and overwrite the values from previous iteration of the 'for' loop.
But to my surprise it is APPENDING, not OVERWRITING.. :( What can be the problem?
I would really appreciate your inputs!! PLEASE help!
Regards
Pramit

Accepted Answer

Jan
Jan on 2 Apr 2015
What about this:
X = out_M_corr(test,2);
Y = out_M_corr(test,3);
  1 Comment
pramit Sood
pramit Sood on 2 Apr 2015
Hey Jan!!
Well I can't help but give thumbs up to you to teach me that thinking simple is the best idea!! It works! :D
Thank you so much!! N Happy Easter!!! Can I send you some chochlates?? :)
Regards
Pramit

Sign in to comment.

More Answers (1)

Roger Stafford
Roger Stafford on 2 Apr 2015
If you want X and Y to be completely overwritten on each trip through the for-loop, you will have to make some provision for their values for the elements for which 'test' is false. Otherwise these "false test" elements, though initially zero, will thereafter be what they were on the previous pass. Probably you should do something like this:
X = zeros(size(out_M_corr,1));
X(test,1) = out_M_corr(test,2);
and similarly for Y.
  2 Comments
pramit Sood
pramit Sood on 2 Apr 2015
Hi! thank you for your reply.. :) Unfortunately that does not help.. as I had tried doing it earlier.. It gives '0's for the old values.. what I want is the old values to be completely deleted and only new values from the current iteration to remain.. :)
Regards
Pramit
pramit Sood
pramit Sood on 2 Apr 2015
Hi Roger!
Thank you for the initiative to help me!!
Joyful easter holidays to you!!
Regards
Pramit

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!