Vectorising conditional for loop

1 回表示 (過去 30 日間)
Melanie VT
Melanie VT 2023 年 3 月 10 日
コメント済み: Melanie VT 2023 年 3 月 10 日
Hi,
I have a code snippet which updates one of the inputs (struct_data2) using a conditional for loop. I tried to implement a vectorised solution but couldn't achieve it. Support on how to cope with this will be greatly appreciated.
Thanks in advance,
Mel
struct_data1 = struct_data1_root;
struct_data2 = struct_data2_root;
empty_struct_data2_idx = cellfun(@isempty, {struct_data2(:).cid}.');
match_idx = find(empty_struct_data2_idx);
for i = 1: height(struct_data1)
cond = struct_data1(i).nid;
if cond > 1
count = size(match_idx, 1);
rand_idx_id = randperm(count, cond-1);
[struct_data2(match_idx(rand_idx_id)).cid] = deal(struct_data1(i).cid);
match_idx = removerows(match_idx, 'ind', rand_idx_id);
end
end
  1 件のコメント
Catalytic
Catalytic 2023 年 3 月 10 日
Please don't .zip your attachments. It makes it harder for us to extract your data and use the Answers run feature.

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

採用された回答

Matt J
Matt J 2023 年 3 月 10 日
編集済み: Matt J 2023 年 3 月 10 日
Perhaps as follows,
empty_struct_data2_idx = cellfun('isempty', {struct_data2(:).cid}.');
match_idx = find(empty_struct_data2_idx);
struct_data1([struct_data1.nid]<=1)=[];
CIDpool=repelem([struct_data1.cid], [struct_data1.nid]-1);
Nmatch=min(numel(match_idx), numel(CIDpool));
CIDpool=num2cell(CIDpool(1:Nmatch));
locations=randperm(numel(match_idx),Nmatch);
[struct_data2(match_idx(locations)).cid]=deal(CIDpool{:});
  1 件のコメント
Melanie VT
Melanie VT 2023 年 3 月 10 日
Works like a charm! Thank you very much @Matt J🙏🏼

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by