2016-08-17 821 views
0

我有三個m文件使用相同的變量並對這些變量進行計算。我創建了一個索引m文件,其中我聲明瞭所有變量,並且可以使用變量名將變量共享給其餘的m個文件。我的問題是變量名稱變化太頻繁,然後我必須手動更改所有這些文件中的變量名稱。我怎樣才能創建一個Matlab腳本,它可以自動從索引m文件獲取變量名稱和值,並將這些文件放到其餘的m文件中。如何在Matlab中的不同m文件之間共享變量

+0

一個解決方案可以通過使用函數和使用變量作爲這些函數的參數。這如何有效地完成? –

+2

這個問題的經典解決方案是創建其他.m文件作爲函數。所以你在myfile.m中運行你的腳本,在你的myfile2.m中調用myfile2()。你能舉一個例子的代碼 – Finn

+0

這ia我的m文件的一部分 %關閉所有; 清除所有; clc; A0 = 0; A1 = 6; A2 = 12; A3 = 13; 保存('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 

,你可以把所有的在你的腳本和嘗試。現在到功能部分。你的功能可以有輸入,輸出,既不是,也有兩者。如果你只是想創建數據,你不需要輸入,但輸出。

保存爲myfile1.m

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 

,這爲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 

現在嘗試

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') 

我希望這將讓你開始。