save values in array in a loop
이전 댓글 표시
I want to save a value calculated inside a loop in an array. Is it possible? for example:
for i=1:10
s=a+b;
a(i)=s;
end
a
ans=
a=[23 45 678 21 34 134 34 56 11 34]
how to save s in an array so that this loop give an array containing the calculated values?
댓글 수: 3
It is not clear what you are trying to do. Which variables do you already know the values of? What are the values of a and b ? Is the operation just a simple addition?
You should consider vectorizing the calculation rather than doing this in a loop. This would likely be neater and faster code!
Sana Tayyeb
2015년 3월 22일
Debasish Roy
2018년 2월 3일
first of all make a script like this, then run it. You will get your answer i hope.
clear all clc
x = []; y = []; k =[]; f = []; for i= 1:4 fprintf('Enter the temperature of day %d \n' ,i ); s = input(' in celcius '); x(i) = s; y(i) = i; end k = x+273; f = x*9/5 + 32; plot( y, x , '-R', y , f ,'-G' ,y ,k, ' -B')
답변 (2개)
Konstantinos Sofos
2015년 3월 21일
x = [] % initialize your matrix/vector
for i=1:10
% do something useful
s=a+b
x = [x,s];
end
댓글 수: 3
There are multiple issues with this code:
- no array preallocation: every loop iteration is going to increase the size of the variable x, which means MATLAB has to check if it still fits in the given memory, and move it if it doesn't.
- concatenation instead of indexing: rather than concatenating s onto x with every iteration, it would be better to simply index into x and assign the values of s.
- the name of the loop variable i shadows the inbuilt names of the imaginary unit. Do not use i or j for variable names.
Rather than learning poor code practices like this, you should consider vectorizing the calculation, which is what MATLAB themselves advise for writing fast and neat code, and will expand neatly to larger data sizes.
As a beginner it is better to learn good code practices from the start, rather than learning poor habits and trying to change them later.
Konstantinos Sofos
2015년 3월 21일
More or less I agree with you...but here we do not have any performance issue question...just a way to keep the values ;)
hemasai proddutur
2021년 7월 7일
d = 0;
for t=1:10000
d = d+0.1;
end
i want to store the values in array in the loop [0.1 -----------------1000]
Anil Kumar
2022년 6월 22일
2 개 추천
may be helpful for begginers
x1=[];
x2=[];
a=[2 4 6 7 3];
b=[1 9 7 5 8];
for ii=1:5
s=a(ii)+b(ii);
x1=[x1,s];%output in a row
x2=[x2;s];%output in a column
end
카테고리
도움말 센터 및 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!