フィルターのクリア

For-Loop Alternative for Faster Code Execution

6 ビュー (過去 30 日間)
RDG
RDG 2013 年 6 月 27 日
Suppose,
a{1}=[1 6;
1 9;
1 8;
3 7;
3 0;
4 0;
5 0;
5 0;
5 0;
5 0;]
desired_answer{1}= [1 6;
1 6;
1 6;
3 9;
3 9;
4 8;
5 7;
5 7;
5 7;
5 7;]
Is there a more efficient way I can do this without having to use for loop? (Cell Array is used because it is adapted from my problem)
  2 件のコメント
Matthew Eicholtz
Matthew Eicholtz 2013 年 6 月 27 日
Can you provide more details? Here is what I conclude from your description: the number of nonzero entries in the second column equals the number of unique values in the first column; then, you want to assign each of the second-column values to all instances of the appropriate first-column value, in order. Is that correct?
RDG
RDG 2013 年 6 月 27 日
The value "6" in column 2 should be assigned to value "1" in column 1, "9" to "3", "8" to "4", "7" to "5".

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

採用された回答

Matthew Eicholtz
Matthew Eicholtz 2013 年 6 月 27 日
Still unsure about your problem setup, but the following code will yield your desired result for the example above.
[~,~,idx] = unique(a{1}(:,1));
a{1}(:,2) = a{1}(idx,2);

その他の回答 (1 件)

Matthew Eicholtz
Matthew Eicholtz 2013 年 6 月 27 日
And if the for loop you are concerned about is looping through the cells in your cell array, then try this code:
[~,~,idx] = cellfun(@(x) unique(x(:,1)),a,'uni',0);
a = cellfun(@(x,y) [x(:,1) y],a,cellfun(@(z,i) z(i,2) ,a,idx,'uni',0),'uni',0);
Perhaps this is not the most elegant solution, in which case I expect the MATLAB pros will chime in shortly.

カテゴリ

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