スクリプトの何行目に​何が書かれているかを​特定する方法はありま​すか?

スクリプトの行数を特定し、その行に書かれているテキスト情報を出力することができる関数はありますか?

1 Comment

Smith David
Smith David on 15 Jan 2024
スクリプトの特定の行に書かれているテキスト情報を取得するための簡単な方法はあります。以下は、MATLABの例ですが、他のプログラミング言語でも同様のアプローチが可能です。
function lineText = getScriptLine(filePath, lineNumber) % ファイルを開く fileID = fopen(filePath, 'r'); % 行ごとにセル配列に読み込む lines = textscan(fileID, '%s', 'Delimiter', '\n'); lines = lines{1}; % ファイルを閉じる fclose(fileID); % 指定された行が存在するか確認 if lineNumber <= numel(lines) % 指定された行のテキストを取得 lineText = lines{lineNumber}; else lineText = '指定された行は存在しません。'; end end
この関数を使用すると、特定のファイルと行数を指定して、その行に書かれているテキスト情報を取得できます。例えば、getScriptLine('yourScript.m', 10)とすると、'yourScript.m'の10行目のテキスト情報が取得されます。他のプログラミング言語でも同様のロジックを使用できます 漫画ロウ

Sign in to comment.

 Accepted Answer

Dyuman Joshi
Dyuman Joshi on 20 Dec 2023

1 vote

See dbtype -
%Using dbtype on the built-in max() function
dbtype max.m
1 function varargout = max(varargin) 2 %MAX Largest component 3 % M = MAX(X) 4 % C = MAX(X,Y) 5 % [M,I] = MAX(X) 6 % [M,I] = MAX(X,[],DIM) 7 % [M,I] = MAX(X,[],...,'linear') 8 % M = MAX(...,NANFLAG) 9 % M = MAX(...,"ComparisonMethod",METHOD) 10 % 11 % Limitations: 12 % Index output is not supported for tall tabular inputs. 13 % 14 % See also: MAX, TALL. 15 16 % Copyright 2015-2023 The MathWorks, Inc. 17 18 try 19 [varargout{1:max(nargout,1)}] = minmaxop(@max, varargin{:}); 20 catch E 21 throw(E); 22 end 23 end

4 Comments

KO
KO on 20 Dec 2023
Is it possible to extract sentence of specific line as a variable like below?
a = dbtype(filename, range)
No, dbtype() can only display the contents -
dbtype magic.m 3:5
3 % MAGIC(N) is an N-by-N matrix constructed from the integers 4 % 1 through N^2 with equal row, column, and diagonal sums. 5 % Produces valid magic squares for all N > 0 except N = 2.
To extract the content as string, use readlines -
in = readlines('magic.m');
out = in(3:5,:)
out = 3×1 string array
"% MAGIC(N) is an N-by-N matrix constructed from the integers" "% 1 through N^2 with equal row, column, and diagonal sums." "% Produces valid magic squares for all N > 0 except N = 2."
KO
KO on 20 Dec 2023
Thank you very much!
You can use either @Dyuman Joshi's or @KO's way of writing (syntax) for dbtype function.
Thank you two for reminding me about the dbtype function.
I had forgotten about it and had been using only the type function.
%Using dbtype on the built-in max() function
% dbtype max.m 5:7"
dbtype('max.m','5:7');
5 % [M,I] = MAX(X) 6 % [M,I] = MAX(X,[],DIM) 7 % [M,I] = MAX(X,[],...,'linear')
% dbtype max.m 5
dbtype('max.m','5');
5 % [M,I] = MAX(X)

Sign in to comment.

More Answers (0)

Products

Release

R2022a

Asked:

KO
on 20 Dec 2023

Commented:

on 15 Jan 2024

Community Treasure Hunt

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

Start Hunting!