# Input data from one array to another

조회 수: 25(최근 30일)
Mathias 2014년 5월 6일
댓글: Mathias 2014년 5월 6일
Hello. I'm currently trying to implement data from a dataset to a variable, as a function of time. I've tried the answers which are already here, but have been unsuccesful.
Current script:
time=365; % [days] Calculation time
dt=0.1; % [days] Timestep
nt=time/dt; % [-] Calculation steps
tempdata is a [365,2] dataset with an index in column 1 and temperature data in column 2.
for i=2:nt
for j=1:365
T(1)=tempdata(1,2); % Starting condition for T, as i=2:nt
Dt(1)=0; % Time elapsed
Dt(i)=Dt(i-1)+dt;
% I want to set up an if function, which takes the temperature data
% from tempdata(j,2) and puts it into T(i), if Dt(i) is equal to
% tempdata(j,1).
if Dt(i)==tempdata(j,1);
T(i)=tempdata(j,2);
else
T(i)=T(i-1);
end
end
end
This function however doesn't work. I firstly don't understand why, and secondly don't know any other way of doing this. Any of you guys know how?
Much appreciated :)
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Mathias 2014년 5월 6일
What I'm trying to do is be able to choose an arbitrary timestep and have it work (as long as dt ends in an integer). I want 'T(i)' to get the value from 'tempdata(j,2)' if the current timestep 'Dt(i)' is equal to the timestep in 'tempdata(j,1)'.
Example:
'tempdata(j,1)' is an index going 1.00, 2.00 ,3.00... while 'Dt(i)' could be anything, eg. 0.33, 0.66, 1.00... So in this example, when i=3 in 'Dt(i)' it should register that this input is the same as j=1 in 'tempdata(j,1)', and then take the j=1 in 'tempdata(j,2)' and use it as an input in 'T(i)'.
Hope that's somewhat understandable.

댓글을 달려면 로그인하십시오.

### 채택된 답변

lvn 2014년 5월 6일
The main problem with your code was the double for loop. Even if a match was found, for say j=50; it was overwritten in the second iteration with j=51 and T(i)=T(i-1); Here is a code that should do what you want:
time=365; % [days] Calculation time
dt=0.1; % [days] Timestep
nt=time/dt; % [-] Calculation steps
Dt=0:dt:365; %So a vector from 0 to 365 in steps of 0.1
T=Dt*NaN; %Define a vector of the same length as Dt, start with NaN's everywhere
T(1)=tempdata(1,2); %First element fixed
for j=1:365 %Put all the exact matches
T(Dt==tempdata(j,1))=tempdata(j,2);
end
for j=2:length(T) %If no match found, put equal to previous element
if isnan(T(j))
T(j)=T(j-1);
end;
end
##### 댓글 수: 1표시숨기기 없음
Mathias 2014년 5월 6일
Thank you ALOT!!! You really saved my day man!

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!