How can I define variables like d12 d23 d24 and so on from a vector containing the values of d and a vector containing the indices?
조회 수: 2 (최근 30일)
이전 댓글 표시
So I have this table of data which is for information of streams from a point to another. So they're given like this right now in my PDF
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/157011/image.png)
I don't want to make 20 lines for d12=0,1;d23=0.08;, etc so I thought of trying to somehow have the values and indices in separate vectors then assign the values to 10 different variables (10 more for the L's) in a for loop. But I can't think of how to achieve this. Right now I have
% Define indices
ind=num2str([12 23 24 34 35 45 36 57 58 49]);
% Define d's
d=[.1 .08 .08 .1 .08 .08 .09 .09 .09 .09];
d2=d.^2;
(the last step is because we will be using only the squares of the d's anyway so might as well assign the squares to my new variables). So I want to somehow use a loop and get d12=.1, d23=.08, L12=1000, L23=800 and so on with 2 for loops instead of 20 lines of assigning variables. I can't use arrays like d(1), d(2), etc like we usually do because it's difficult to keep track of what streams the d and L is for then.
댓글 수: 0
채택된 답변
Walter Roberson
2016년 10월 8일
Use cell arrays d{12}, d{23} and so on.
댓글 수: 2
Marc Jakobi
2016년 10월 8일
I would not index the cell arrays with d{12}, d{23}, etc. though. That makes the arrays a lot larger than they need to be. You don't really need cell arrays for this at all.
If you really want to keep the indexes 12, 23, 24, 34, etc., add them to another array or vector and index the cell array or vector with 1, 2, 3, ...
You could still access them like this:
ind=num2str([12 23 24 34 35 45 36 57 58 49]);
d=[.1 .08 .08 .1 .08 .08 .09 .09 .09 .09];
to access d34, you could access it like this:
d(ind == 34)
Walter Roberson
2016년 10월 9일
Cell array entries that have never had anything stored into them require 8 bytes of storage.
Cell array entries that have had something stored into them add an extra 104 bytes plus the amount of storage required for the data; the extra 104 bytes does not go away if you store [] over the entry. Somehow, the internal code knows the difference between "this is zeros(0,0,'double') because it has never been initialized" and "this is zeros(0,0,'double') because that is what has been stored here".
Thus, using d{12}, d{23}, and so on, only requires 8 extra bytes per unused cell. That probably is not going to add up to much. It would require time to have a vector like [11 12 21 22 23] that you searched to find the index of (say) 23 in order to find the index into a compact cell array -- it could be done, but it is not clear that it is worthwhile unless you get into large indices.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!