find element inside cell
16 次查看(过去 30 天)
显示 更早的评论
A={[1,2,4],[2,3,4],[2,4,5],[4,5,6,9,10,11],[4,7,9],[7,8],[6,12,13],[4,5,6,7]};
base={[2],[1],[1],[3],[2],[1],[1],[1]};
first_element=cellfun(@(v)v(1),A,'UniformOutput',false);
result=cellfun(@(m,v)m(find(v==1)),A,base,'UniformOutput',false);
I want to change order of cell A, according to base. base that has [1] should come first
result should be
A={[2,3,4],[2,4,5],[7,8],[6,12,13],[4,5,6,7],[1,2,4], [4,7,9],[4,5,6,9,10,11]};
2 个评论
Guillaume
2019-3-1
result should be A={[2,3,4],[2,4,5],[7,8],[6,12,13],[4,5,6,7],[1,2,4], [4,7,9],[4,5,6,9,10,11]};
Your code is never going to produce anything like that, and it's really not clear how you'd get that result with the base you've given. You could obtain that result with:
result = A([2, 3, 6, 7, 8, 1, 5, 4])
As can be clearly seen in the text of the error message, the code that produces the error is not the same code you show in your question.
%code in the question
result = ...
%code that produces the error
[~, ids] = ...
And yes, [~, ids] = ... is going to produce an error as you ask for the second output of something that only produces one.
All in all, it's very unclear what you're trying to do. It would be simpler if you told gave us details of the general problem.
采纳的回答
Guillaume
2019-3-1
Oh! That's easy then.
First, there's no need for index_base to be a cell array. It uses 15 times more memory than a simple vector for no benefit.
index_base = [2 1 1 3 2 1 1 1]; %use exactly 15 times less memory than a cell array
If for some reason, it has to start as a cell array, we do need it as a matrix anyway, so:
%index_base = {2 1 1 3 2 1 1 1};
index_base = cell2mat(index_base); %we need a matrix
Then,
[~, order] = sort(index_base);
result = A(order);
1 个评论
Guillaume
2019-3-1
I think you would be better off starting a new question for that.
If the code you've written doesn't do what you want I would recommend that you don't put it in the question as that's a bit confusing. Rather give the starting point (A, ref, and index_base if it's needed), what you want to obtain and explain in words how to get there (bullet points detailing the steps would be ideal).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!