How do I create array of a function with for loop?

조회 수: 8 (최근 30일)
N/A
N/A 2021년 9월 7일
댓글: Stephen23 2021년 9월 10일
Hi, I am trying to find a shorter and easier for my calculations. I have a in total 42 of 424x412 doubles for which I want to calculate the mean of all elements and build an array of the results that would be 42x1. So far I have done that the following way
B = [mean(X1,'all');mean(X2,'all');..mean(X42,'all')]
Since I have to calculate such arrays multiple times (I have do that for multiple sets of 42 arrays) I would much rather like to that in a for-loop..so far i have tried the following, which didn't work
for k = 1:42
B = mean('X(k)','all')
end;
can somebody help me?
I am a MATLAB rookie! :D
  댓글 수: 1
Stephen23
Stephen23 2021년 9월 7일
You did not tell us the most important information: how did you get 42 numbered variables into the workspace?
Did you sit and write out their names by hand? Or generate them in a loop? Or load them from file?
In any case, that is where you need to fix your code, rather than trying to fix the problem later:

댓글을 달려면 로그인하십시오.

답변 (2개)

Steven Lord
Steven Lord 2021년 9월 7일
I have a in total 42 of 424x412 doubles
Can you do this? Yes.
Should you do this? The general consensus is no.
Rather than having 42 individual variables why not make a 42-by-424-by-412 array?
  댓글 수: 2
N/A
N/A 2021년 9월 7일
I'd like to have that 42x1 for later calculations...
And I also have to do that multiple times... The X in the example above stands for a month... I want to calculate that for all 12 months and over muliptle datasets
Stephen23
Stephen23 2021년 9월 7일
"And I also have to do that multiple times... The X in the example above stands for a month... I want to calculate that for all 12 months and over muliptle datasets "
Sure. That would be easy and very efficient using standard MATLAB coding, e.g. using indexing to access data in arrays (which could be container arrays). Is there any particular reason why you want to force yourself into writing slow, complex, obfuscated, inefficient code?

댓글을 달려면 로그인하십시오.


Mathieu NOE
Mathieu NOE 2021년 9월 7일
hello
it's not the best coding practice, but it works ...
clc
clearvars
% dummy data
X1 = rand([424,412]);
X2 = rand([424,412]);
X3 = rand([424,412]);
% main code
for k = 1:3
B(k) = mean(eval(['X' num2str(k)]),'all');
end;
plot(B,'*')
  댓글 수: 3
Mathieu NOE
Mathieu NOE 2021년 9월 8일
hello
if my answer has helped you , would you mind accepting it ?
tx
Stephen23
Stephen23 2021년 9월 10일
Note that this approach will not help you, it will hinder you.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by