필터 지우기
필터 지우기

How to quickly index the first cell of sets of the array with near similar names?

조회 수: 2 (최근 30일)
Hey all, Here is my workspace:
I want to know if there is any way to index the first cell of each P_ arrays based on (Jan, Feb, Mar,..., Dec, Win, Spr, Sum, Aut, Annual)
For example in this picture I want :
8, 12, 5, 8, 9, 8 , 7, 5, 5, 6, 6, 7, 7, 5, 2, 3, 8
(January to annual)
Thank you all
  댓글 수: 1
Stephen23
Stephen23 2020년 4월 21일
편집: Stephen23 2020년 4월 21일
Bad data design forces you to write slow, complex, obfuscated, buggy code which is hard to debug:
Your code would be simpler and more efficient if you just used a structure, e.g.:
S.Jan = [...]
S.Feb = [...]
...
S.Dec = [...]
Then you could use dynamic fieldnames to access any of the arrays:
fld = 'Jan';
S.(fld)
Or use a table, which would be similarly simple and efficient to access:
Note that you should fix your badly-designed data at the point where those separate arrays are generated in the workspace, e.g. by load-ing into an output variable (which is a scalar structure) instead of directly into the workspace:
S = load(...)

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

채택된 답변

Mehmed Saad
Mehmed Saad 2020년 4월 21일
편집: Mehmed Saad 2020년 4월 21일
You can do that using eval but it is not efficient to use eval in your code frequently
mn={'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Win','Spr','Sum','Aut','Anuual'};
x = zeros(1,length(mn));
for i=1:length(mn)
x(i) = eval(['P_' mn{i} '(1)']);
end

추가 답변 (2개)

Rik
Rik 2020년 4월 21일
This is bad code design. You should have made these variables fields of single struct. This has forced you to write slow buggy code where you are forced to either write a lot of repetitive code by hand, or use eval. You should change how this data was generated.
Once it is a struct you can use the code below.
fn=fieldnames(P);
output=zeros(size(fn))
for n=1:numel(fn)
tmp=P.(fn{n});
output(n)=tmp(1);
end

KSSV
KSSV 2020년 4월 21일
YOu can get the variable names into a cell and use strcmp to check the variable.
S = whos ;
v = {S.name} ;
idx = strfind(v,'P_Jan') ;
  댓글 수: 2
BN
BN 2020년 4월 21일
Well, Thank you but I'm sorry, I want an entirely different thing. I wanted to index the first value of each array.
KSSV
KSSV 2020년 4월 21일
Use logical indexing......
idx = find(myarray == num) ;

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by