Matrix call inside a for loop

3 ビュー (過去 30 日間)
Felix
Felix 2017 年 8 月 16 日
コメント済み: Felix 2017 年 8 月 28 日
I probably have an easy equation regarding the correct vector calling inside a for-loop. I’m trying to conduct the same calculation for let’s say different 4 vectors. Therefore I would like to use a for-loop. Simplified, it should look like this:
a_1 = [1 2 3 4 5]
a_2 = [2 3 4 5 6]
a_3 = [3 3 4 5 7]
a_4 = [4 3 4 5 8]
for i=1:4
b(i)=a_(i)/60
end
  4 件のコメント
Stephen23
Stephen23 2017 年 8 月 20 日
編集済み: Stephen23 2017 年 8 月 20 日
"I want to invoke different matrix/arrays to use them inside subplot and for further calculations."
We already explained why this is a bad idea: it will make your code slow, buggy, and complex. It is so hard you had to ask on an internet forum for help. Why bother? If you simply stored your data in one array then you can trivially use indexing: indexing is simple, fast, neat, efficient, easy to debug.
Felix
Felix 2017 年 8 月 28 日
Thanks for your help.
%
x = [1 2 2 3 3 4]
y = [0 0 1 1 0 0 ;0 0 2 2 0 0; 0 0 3 3 0 0;0 0 4 4 0 0]
for i=1:4
subplot(2,2,i)
plot(x,y(i,:),'linewidth',2)
axis([0 5 0 5])
end

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

採用された回答

Stephen23
Stephen23 2017 年 8 月 20 日
編集済み: Stephen23 2017 年 8 月 20 日
If you simply put all of your data into one array then your task is trivial using indexing:
Time = [0 1 1 3 3 4];
Data = [0 0 2 2 0 0;...
0 0 3 3 0 0];
cutoff = 1;
idx = Time>=0 & Time <= cutoff;
for k = 1:size(Data,1)
subplot(2,1,k)
plot(Time(idx),Data(k,idx),'r','LineWidth',2)
org = trapz(Data(k,:));
off = trapz(Data(k,idx));
out = off ./ org
end
and it displays these outputs:
out =
0.25
out =
0.25
By using better data design (using one numeric matrix for all data) I wrote more working code in less time than it took you to write your last comment. Good design makes code simpler and more efficient. Ignore whatever bad advice other beginners might give you, do NOT try to access variable names dynamically, doing so is worse code than you can imagine:

その他の回答 (1 件)

José-Luis
José-Luis 2017 年 8 月 16 日
編集済み: José-Luis 2017 年 8 月 16 日
data = {a1,a2,a4,a4}; %Better yet, use a cell array from start
result = cell(size(data));
for ii = 1:numel(data)
b(ii) = a{ii}./60;
end
You could also use cellfun() to avoid looping.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by