Help Using Variable In Workspace in For Loop

5 ビュー (過去 30 日間)
Kristine
Kristine 2025 年 4 月 30 日
コメント済み: Kristine 2025 年 4 月 30 日

Hi y’all,

I have a variable in my Workspace that I want to reference in my for loop, but it doesn’t work. It only works if I define that same variable in my loop. How can I fix this?

output_folder_location = '/Users/blah_blah/Test_Output' ; % variable in Workspace
function [] = each_day_table(folder_referenced)
 dimention = size(folder_referenced) ; 
   for i = 1:dimention(2)
    datastore_result = datastore(folder_referenced(i)) ;
    original_data = readall(datastore_result) ; 
    with_datetime = add_datetime_column(original_data, folder_referenced(i)) ; 
    [folder, name, ext] = fileparts(folder_referenced(i)) ; 
    output_filename = fullfile(output_folder_location, "new_" + name + ext) ; % where I’m referencing variable from Workspace 
    writetable(with_datetime, output_filename) % Saving files.
    end 
end

It only works when I do:

   …
   [folder, name, ext] = fileparts(folder_referenced(i)) ; 
   output_folder_location = '/Users/blah_blah/Test_Output' ; % Defining variable here 
   output_filename = fullfile(output_folder_location, "new_" + name + ext) ;
   writetable(with_datetime, output_filename) % Saving files.
   … 

採用された回答

Cris LaPierre
Cris LaPierre 2025 年 4 月 30 日
編集済み: Cris LaPierre 2025 年 4 月 30 日
Your for loop has been defined inside a function. Functions have their own workspace. You need to either pass the variable into the function as an input argument or define it inside the function.
output_folder_location = '/Users/blah_blah/Test_Output' ; % variable in Workspace
function [] = each_day_table(folder_referenced,output_folder_location)
dimention = size(folder_referenced) ;
for i = 1:dimention(2)
datastore_result = datastore(folder_referenced(i)) ;
original_data = readall(datastore_result) ;
with_datetime = add_datetime_column(original_data, folder_referenced(i)) ;
[folder, name, ext] = fileparts(folder_referenced(i)) ;
output_filename = fullfile(output_folder_location, "new_" + name + ext) ; % where I’m referencing variable from Workspace
writetable(with_datetime, output_filename) % Saving files.
end
end
  1 件のコメント
Kristine
Kristine 2025 年 4 月 30 日
Ah! That was so simple, I don't know how I overlooked that. Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by