이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
How to modify this code to make it import values from a file?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi,
The following code opens a file (named "Pulse.acc") and writes c, s and t values as follows:
0 1 0
0 2 0
0 3 0
It also opens another file (named :Case.tcl") and writes each case number.
Each case over-writes the previous one.
I am now trying to import the values of s from the attached file (named "result_40.txt"). This file contains 40 columns and 10 rows. Each value in the columns will be printed in "Pulse.acc" file and excute OpenSees software model (along with c and t values. For example: 0 1 0, as shown above). This needs to continue until the 10th value in the column. Then, the second column starts.
The values of c and t will continue to be zero, so they could be left as below.
It would be great if a folder can be opened for the outputs from each column and numbered sequentially.
I hope I could explain what I want clearly, and please feel freel to let me know if I need to explain it further.
c=[0 0 0];
s=[1 2 3];
t=[0 0 0];
for j = 1:3
fidP = fopen('Pulse.acc','w+');
fidC= fopen('Case.tcl','w+');
fprintf(fidP, '%d\n%d\n%d',c(j), s(j), t(j));
fprintf(fidC, 'set case %d',j);
fclose(fidP);
fclose(fidC);
!OpenSees Model.tcl
end
채택된 답변
Bob Thompson
2019년 2월 19일
Importing and reading the data into matlab is fairly simple, and you can take your pick of text readers. It sounds like dlmread will work best for what you're trying to accomplish here so I will use that. Alternatively, you can investigate textscan(), csvread(), or just fopen() with fgetl().
fin = 'result_40.txt';
s = dlmread(fin,'');
c = 0;
t = 0;
for i = 1:size(s,2);
coldir = mkdir(['Column_',num2str(i)]);
cd(coldir);
for j = 1:size(s,1);
fidP = fopen('Pulse.acc','w+');
fidC= fopen('Case.tcl','w+');
fprintf(fidP, '%d\n%d\n%d',c, s(j,i), t);
fprintf(fidC, 'set case %d',j);
fclose(fidP);
fclose(fidC);
end
cd('../');
end
댓글 수: 24
Ismail Qeshta
2019년 2월 19일
Hi Bob,
Many thanks for your reply and the suggested code.
I tried it but I keep getting the following error message:
Error using cd
Path must be a string scalar or character vector.
Error in Frag2Ffyn (line 49)
cd(coldir);
Ismail Qeshta
2019년 2월 19일
편집: Ismail Qeshta
2019년 2월 19일
Hi Stephen,
Thank you for your feedback. Would it be possible to explain where to get filepaths codes?
Bob Thompson
2019년 2월 19일
Getting a file path is simply defining it in a variable. So, what Stephen is talking about is that instead of using cd() to change the directory you're working in, just define a specific path within the variable itself.
parentdir = 'C:\Users\bob\mytestfolder\';
... % Other bits of code I wrote already
for i = 1:size(s,2);
coldir = mkdir([parentdir,'Column_',num2str(i)]);
% We don't need cd() anymore
for j = 1:size(s,1);
fidP = fopen([coldir,'\Pulse.acc'],'w+');
fidC= fopen([coldir,'\Case.tcl'],'w+');
end
end
Ismail Qeshta
2019년 2월 19일
Hi Bob,
Many thanks for correcting the code. I still get this error message:
Error using horzcat
The following error occurred converting from logical to char:
Conversion to char from logical is not possible.
Error in Frag2Ffyn (line 52)
fidP = fopen([coldir,'\Pulse.acc'],'w+');
Bob Thompson
2019년 2월 19일
Change the following.
coldir = mkdir([parentdir,'Column_',num2str(i)]); % old
mkdir([parentdir,'Column_',num2str(i)]); %new
coldir = [parentdir,'Column_',num2str(i)];
Ismail Qeshta
2019년 2월 19일
편집: Ismail Qeshta
2019년 2월 21일
Hi Bob,
Many thanks for your corrections.
I have tried to run the code.
Below you can see the directory where I am trying to excute the OpenSees model. I need to create folders for each column in the BridgePier foler (last folder in the directory).
However, the output files are printed in a file inside the that folder and no column files were created.
In other words, I actually need to create the Pulse.acc and Case.tcl in BridgePier folder, while creating the column1, column2, ... , column 40 in BridgePier folder.
The code:
parentdir = 'C:\Users\ismai\Desktop\B - SI\26\fgfg\BP';
fin = 'result_all.txt';
s = dlmread(fin,'');
c = 0;
t = 0;
for i = 1:size(s,2);
mkdir([parentdir,'Column_',num2str(i)]); %new
coldir = [parentdir,'Column_',num2str(i)]; % We don't need cd() anymore
for j = 1:size(s,1);
fidP = fopen([coldir,'\Pulse.acc'],'w+');
fidC= fopen([coldir,'\Case.tcl'],'w+');
!OpenSees Model.tcl
end
end
cd('../');
Bob Thompson
2019년 2월 19일
This is a simple adjustment. All you need to do is change our directory variable for printing the files. Currently you are printing them to 'coldir' which is a combination of the parent directory and the column folder contained within the parent. If you want to put Pulse and Case within the parent directory then just change the fopen() command to call the parent directory instead of the 'coldir' directory.
Ismail Qeshta
2019년 2월 19일
편집: Ismail Qeshta
2019년 2월 19일
Hi Bob,
Many thanks for your clarification. The 40 folders are still printed in the ModelValidation folder. I need them to be printed in BridgePier folder instead.
Ismail Qeshta
2019년 2월 19일
편집: Ismail Qeshta
2019년 2월 19일
I think I am getting a little confused Bob.
I will double-check what procedures I exactly need with respect to folders and get back to you tomorrow.
Thank you.
Bob Thompson
2019년 2월 19일
You need to add a slash in between your parent directory and your new folders. If you look at the directory being created it currently looks like this:
[parentdir,'Column_',num2str(i)]
% 'C:\Users\ismai\Desktop\Bridge under Tsunami - SI\eleLoad\ModelValidation\BridgePierColumn_#
It should look like this:
'C:\Users\ismai\Desktop\Bridge under Tsunami - SI\eleLoad\ModelValidation\BridgePier\Column_#
You can achieve this either by adding the slash to your parent directory definition, or to the mkdir command.
parentdir = 'C:\Users\ismai\Desktop\Bridge under Tsunami - SI\eleLoad\ModelValidation\BridgePier\';
or
mkdir([parentdir,'\Column_',num2str(i)]);
Ismail Qeshta
2019년 2월 19일
Thank you Bob for the correction and clarification. I have just corrected that.
Actually, I just found that there not data printed in the Case.tcl and Pulse.acc files.
The other thing that I am double-checking now is that the output files for each column need to be printed inside each column folder.
Bob Thompson
2019년 2월 19일
Checking output file locations should be very similar to what we just did.
For the lack of data printed to the two other files, I would double check that they are opening properly. You can do this by putting a debug flag on the line of your code which contains the write command, and checking to see if fidP or fidC are positive integers. If they are then the files are opening properly.
Ismail Qeshta
2019년 2월 19일
Hi Bob,
Thank you very much for all your effort and time. I have just been thinking of the code and folders arrangements.
I think I can just ignore the idea of creating folders for each column, as I just discovered that it confuses a lot the OpenSees model.
Would it be possible if the code counts all column data sequentially?
It is basically the original code in my post, but instead it imports the data from file and counts each number for s. There is no need to create folders for each column.
Bob Thompson
2019년 2월 19일
What exactly do you mean by 'count?' The for loops with indexes 'i' and 'j' will step through each of the values of s, and you can use that same indexing method to create individual files, or store the data in a single variable.
Ismail Qeshta
2019년 2월 19일
편집: Ismail Qeshta
2019년 2월 19일
Thank you very much Bob.
Yes, I just did it. I cannot thank you enough for all your help and patience while developing the codes. I have just checked it and it worked.
For your kind reference:
fin = 'result_all.txt';
s = dlmread(fin,'');
c=[0 0 0 0 0 0 0 0 0 0 0 0];
t=[0 0 0 0 0 0 0 0 0 0 0 0];
for j = 1:12
fidP = fopen('Pulse.acc','w+');
fidC= fopen('Case.tcl','w+');
fprintf(fidP, '%d\n%d\n%d',c(j), s(j), t(j));
fprintf(fidC, 'set case %d',j);
fclose(fidP);
fclose(fidC);
!OpenSees Model.tcl
end
Ismail Qeshta
2019년 2월 20일
편집: Ismail Qeshta
2019년 2월 20일
Hi Bob,
I have just noticed that the above code rounds the values that are read from "result_all".
For example, 189489.4 becomes 189000.
Would it be possible if the code can read the exact values? just for more accuracy of my results.
Bob Thompson
2019년 2월 20일
Are you sure that Matlab is actually rounding the values? The default display format for matlab is 'short' so it doesn't display more than about 4 sig figs. Try setting your display settings to 'long'
format long
Ismail Qeshta
2019년 2월 20일
Hi Bob,
Many thanks for the suggestion. I set it to "long", but nothing changed.
format long
fin = 'result_all.txt';
s = dlmread(fin,'');
c=[0 0 0 0 0 0 0 0 0 0 0 0];
t=[0 0 0 0 0 0 0 0 0 0 0 0];
for j = 1:12
fidP = fopen('Pulse.acc','w+');
fidC= fopen('Case.tcl','w+');
fprintf(fidP, '%d\n%d\n%d',c(j), s(j), t(j));
fprintf(fidC, 'set case %d',j);
fclose(fidP);
fclose(fidC);
!OpenSees Model.tcl
end
Bob Thompson
2019년 2월 20일
To the best of my knowledge, dlmread does not round data when it loads it from a file. As I said, Matlab might display a rounded value, but the stored data should be the original. Is the data in the text file 189489.4 or 189000? The dlmread command is limited in its fidelity by the fidelity of the file. If the file is only displaying 189000 then it is not possible for the dlmread command to get 189489.4 from that.
Also, the format(long) command does only change the actual 'displayed' value. So if you are not displaying a value then it will not look any different. Try using the format(long) command directly in the command window, and then displaying some value of 's'. See if it has the fidelity you're looking for.
Ismail Qeshta
2019년 2월 20일
Hi Bob,
In the original text file, it is 189489.4
In the "Pulse.acc" it is 189000
Ismail Qeshta
2019년 2월 20일
편집: Ismail Qeshta
2019년 2월 20일
Thank you Bob. I think I just got it. The "rounding" or "display" of "digits" or "zeros" was due to the "copy" and "paste" from Excel sheet to text file.
Since Excel uses E format, the data copied to the text file are rounded.
Apologies for this confusion.
Bob Thompson
2019년 2월 20일
Ah, I see. That is because you're printing with the fprintf command as a double. Try the following:
fprintf(fidP, '%f\n%f\n%f',c(j), s(j), t(j));
You want to print the values as a 'floating point number' rather than a double in order to get the level of fidelity you're looking for. Sorry I didn't catch that earlier.
Ismail Qeshta
2019년 2월 20일
I see. Thank you very much Bob. That is so kind of you. Alright, I will incorporate this correction in the code.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Low-Level File I/O에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)