2016-08-17 37 views
0

同じ変数を使用し、これらの変数に対して計算を実行する3つのmファイルがあります。私はすべての変数を宣言したインデックスmファイルを作成し、変数名を使用して残りのm個のファイルに変数を共有することができます。私の問題は、変数名が頻繁に変更され、これらのファイルすべての変数名を手動で変更する必要があることです。変数名と値をインデックスmファイルから自動的に取得し、残りのm個のファイルに入れるMatlabスクリプトを作成するにはどうすればよいですか?Matlabの異なるmファイル間で変数を共有する方法

+0

1つの解決方法は、関数を使用し、これらの関数の引数として変数を使用することによって行うことができます。どのようにこれを効率的に行うことができますか? –

+2

この問題の古典的な解決策は、他の.mファイルを関数として作成することです。 myfile.mでスクリプトを実行し、その中でmyfile2.mをmyfile2()と呼びます。あなたはコードの少しの例を投稿できますか? – Finn

+0

これは私のファイルの一部です %close all; すべてをクリアします。 clc; A0 = 0; A1 = 6; A2 = 12; A3 = 13;save( 'exp.mat'、 'A0'、 'A1'、 'A2'、 'A3'); これはデータを効率的に共有する方法ではないことがわかります。しかし、私は機能に新しいです。どのように関数を使うことができますか?あなたは私にスタートアップを与えることができますか? –

答えて

0

ここではどこに行くことができるか少しの例が必要なような気がします。 最初に異なる値で各値を呼び出します。同じタイプの値が大量にある場合、配列は次のように簡単です。

A0=0; A1=6; A2=12 %each one with its own name 
B=zeros(16,1); %create an array of 16 numbers 
B(1)= 0; %1 is the first element of an array so care for A0 
B(2)= 6; 
B(8)= 12; 
disp(B); % a lot of numbers and you can each address individually 
disp(B(8)); %-> 12 

これをスクリプトに入れて試すことができます。今機能部に。あなたの関数は、入力、出力、いずれか、またはその両方を持つことができます。データを作成したいだけなら、入力は必要ありませんが、出力は必要ありません。 myfile2.m

function output = myfile2(input) 

input=input*2;%double all the numbers 
%This will make an error if "input" is not an array with at least 3 
%elements 
input(3)=input(3)+2; %only input(3) + 2; 
output = input; 

end 

として

function output = myfile1() 

number=[3;5;6]; %same as number(1)=3;number(2)=5;number(3)=6 
%all the names just stay in this function and the variable name is chosen in the script 
output = number; %output is what the file will be 

end 

、これを、今、私はこれがあなたが始めることを願っています

B=myfile1() %B will become the output of myfile1 
C=myfile2(B) %B is the input of myfile2 and C will become the output 
save('exp.mat','C') 

を試してみてください。

myfile1.mとしてこれを保存します。

関連する問題