generate and save numerous datas in one code then load them in another code

1 visualizzazione (ultimi 30 giorni)
Hi there, if I have two code 'A.m' and 'B.m' under the same file. In 'B.m' I will generate a few variables. I want to save those variables and then load them in 'A.m'. For example, I have p=randi([-5,5]); q=randn(3,2) in 'B.m', somehow I save them, then in 'A.m', after load, the p and q will appear in 'A.m' directly and can use them directly, just like after load , in the next line I can operate 'n=p+q'.

Risposte (1)

VBBV
VBBV il 10 Gen 2023
% in A.m file
[p,q] = B % call the function wbich returns those outputs variables (values)
p = 3
q = 3×2
-2.0504 -0.5961 0.0466 1.8645 -0.2761 2.0829
n = p + q % add them directly as you wanted
n = 3×2
0.9496 2.4039 3.0466 4.8645 2.7239 5.0829
% in B.m save this in another m file with same name (say) B and in same
% folder
function [p,q] = B
p = randi([-5,5]);
q = randn(3,2);
end
  3 Commenti
mingcheng nie
mingcheng nie il 11 Gen 2023
Hi, thank you for you answer. However, I know the 'function' way, the reason I want to do the 'save' and 'load' is that I will have huge datas generated from different distribution in B.m, so I want generate those data first, then load them to my main function, so that I don't need to generate those datas each time I run the main function. I gave the example p and q just for simple understanding of my question. In my actual code, B.m will contains 12 variables, each variables will extract value from different distribution for 20000 times.
VBBV
VBBV il 11 Gen 2023
Modificato: VBBV il 11 Gen 2023
In that case, you can load the data files( preferably *.mat) into workspace using a for loop
for k = 1:length(Files)
K{k} =
load(sprintf('file%d.mat',k));
end
K is an array of structures which contains data fields from each individual data file. This can accessed conveniently inside another loop in the main function including data present its fields. Hope it helps. Files is the number of data(mat) files present accessed.

Accedi per commentare.

Tag

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by