How do I add values to a vector instead of replacing them?

1 回表示 (過去 30 日間)
Skyer
Skyer 2018 年 10 月 19 日
コメント済み: Star Strider 2018 年 10 月 19 日
Hey I'm trying to combine all IDs for pictures into a vector to use in a function but when I write this loop the values get replaced and i only get the value of the last i.
for i = 1:(length(p))
allIDs = [p(i) ImageIDs(1) ImageIDs(2) ImageIDs(3) ImageIDs(4)];
end
If I write "allIDs(i)" instead I get an error message saying they aren't compatible. How can I write this loop instead? Any help would be appreciated.

採用された回答

Star Strider
Star Strider 2018 年 10 月 19 日
Use a row and ‘default’ column subscript for allIDs:
allIDs(i,:) = [p(i) ImageIDs(1) ImageIDs(2) ImageIDs(3) ImageIDs(4)];
That should work.
  4 件のコメント
Skyer
Skyer 2018 年 10 月 19 日
Thank you! You've saved my friday evening.
Star Strider
Star Strider 2018 年 10 月 19 日
As always, my pleasure!

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

その他の回答 (2 件)

YT
YT 2018 年 10 月 19 日
I think you meant to do
allIDs(i,:)
  1 件のコメント
Skyer
Skyer 2018 年 10 月 19 日
Thanks for the answer, but I want them all to be on a single row in the new vector. Is this possible to do?

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


Guillaume
Guillaume 2018 年 10 月 19 日
All the answers assume you want to create a matrix, I'm not sure that's what you want since you mention a vector. In any case, I see nothing in the code given that warrants a loop, so allIDs as a matrix could be created in one fell swoop with:
allIDs = [p(:), repmat(ImageIDs(1:4), numel(p), 1)];
As said, I'm not convinced that's what's desired but if it's not a better explanation is required, in particular, an explanation of what p and ImageIDs are (size, type).
  1 件のコメント
Skyer
Skyer 2018 年 10 月 19 日
Thanks for the answer. I get an error message "Error using horzcat Dimensions of arrays being concatenated are not consistent." using this. Do you know what it means and how to fix it?

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by