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!