How can i create a for loop that modifies a column in an existing matrix?
1 回表示 (過去 30 日間)
古いコメントを表示
Tore Henriksen Eliassen
2020 年 9 月 22 日
コメント済み: Tore Henriksen Eliassen
2020 年 9 月 22 日
So i want to make a for loop that takes the startmatrix(given under):
dicevalue = [1,2,3,4,5,6]';
zeroes = [0,0,0,0,0,0]';
startmatrix = [dicevalue,zeroes];
Startmatrix =
1 0
2 0
3 0
4 0
5 0
6 0
Then replaces the zeroes with the values from amount(given under) according to the values from throwvalues(given under)
throw = [1,1,3,4,5,1];
throwvalues = unique(throw)';
amount = histc(throw(:),throwvalues);
throwmatrix = [throwvalues,amount];
Throwmatrix =
1 3
3 1
4 1
5 1
My overall hope is that i somehow can make a matrix that combines the values from 1 to 6 with the values from my amount variable to in the end get something like this:
Finishedmatrix =
1 3
2 0
3 1
4 1
5 1
6 0
Thankful for all help i can get :)
0 件のコメント
採用された回答
the cyclist
2020 年 9 月 22 日
A = [1,1,3,4,5,1];
dicevalue = [1,2,3,4,5,6]';
throwCounts = histcounts(A,[dicevalue; Inf])';
output = [dicevalue, throwCounts];
3 件のコメント
the cyclist
2020 年 9 月 22 日
I am wary of the use of the phrase, "any unknown A". I mean, it will not work if someone enters the cell array {'x','y','zebra'}.
But it should work for a row vector of any length that contain values 1:6.
This is your code, so you're the one who needs to reach a level of understanding of the histcounts function that makes you confident it does what you need. Beware of blindly using code from the internet that you've not made an effort to understand.
その他の回答 (1 件)
Ameer Hamza
2020 年 9 月 22 日
編集済み: Ameer Hamza
2020 年 9 月 22 日
If startmatrix and throwmatrix follow the same pattern as you gave in the question, i.e., the first columns of both matrices are always in increasing order, then you can do something like this.
A = [1,1,3,4,5,1];
dicevalue = [1,2,3,4,5,6]';
zeroes = [0,0,0,0,0,0]';
startmatrix = [dicevalue,zeroes];
throwmatrix = [1 3; 3 1; 4 1; 5 1];
idx = ismember(startmatrix(:,1), throwmatrix(:,1));
startmatrix(idx, 2) = throwmatrix(:, 2);
Result
>> startmatrix
startmatrix =
1 3
2 0
3 1
4 1
5 1
6 0
Alternative solution:
A = [1,1,3,4,5,1];
dicevalue = [1,2,3,4,5,6]';
zeroes = [0,0,0,0,0,0]';
startmatrix = [dicevalue,zeroes];
throwmatrix = [1 3; 3 1; 4 1; 5 1];
startmatrix(throwmatrix(:,1), 2) = throwmatrix(:,2);
4 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!