How to iteratively append elements to an array
2 次查看(过去 30 天)
显示 更早的评论
I = imread(chart_image);
R = I(:,:,1);
G = I(:,:,2);
B = I(:,:,3);
N= zeros(24,3);
final_chart =zeros (24,3);
Vals = [175 175; 425 175; 650 175; 925 175;
175 420; 425 420; 650 420; 925 420;
175 670; 425 670; 650 670 ; 925 670 ;
175 925; 425 925; 650 925; 925 925;
175 1170; 425 1170; 650 1170; 925 1170;
175 1425; 425 1425 ; 650 1425 ; 925 1425];
for i = 1:24
N(i)=[R(Vals(i,1),Vals(i,2)) G(Vals(i,1),Vals(i,2)) B(Vals(i,1),Vals(i,2))];
final_chart % the variable I want to modify to be able to store the vales of all N as it iterates over the 24 values in Vals into a single 24x3 matrix
end
hello, I wanted to add the value of each N to a final array called final_chart, but I keep getting error "Unable to perform assignment because the left and right sides have a different number of elements.", I've tried other ways to append but for some reason I keep failing all of those. Can someone help me understand where I'm going wrong and help me fix my code. Thank you.
2 个评论
Guillaume
2019-4-9
I don't see how you can get the error "Unable to perform assignment because the left and right sides have a different number of elements" from the code you've posted, since there's no indexing on the left-hand side of any the assignment lines. This error would only occur if you'd written
N(i, :) = ...
%not N(i) = ...
It's not clear what you're trying to do. Your current code overwrites N at each step, so only the value calculated on the last step is retained.
采纳的回答
Guillaume
2019-4-9
If I understood what you're trying to do, there's no need for the loop:
I = imread(chart_image);
R = I(:,:,1);
G = I(:,:,2);
B = I(:,:,3);
Vals = [175 175; 425 175; 650 175; 925 175;
175 420; 425 420; 650 420; 925 420;
175 670; 425 670; 650 670 ; 925 670 ;
175 925; 425 925; 650 925; 925 925;
175 1170; 425 1170; 650 1170; 925 1170;
175 1425; 425 1425 ; 650 1425 ; 925 1425];
locations = sub2ind(size(R), Vals(:, 1), Vals(:, 2));
N = [R(locations), G(locations), B(locations)];
You don't even need to separate the image into colour planes:
I = imread(chart_image);
[width, height, ~] = size(I);
Vals = [175 175; 425 175; 650 175; 925 175;
175 420; 425 420; 650 420; 925 420;
175 670; 425 670; 650 670 ; 925 670 ;
175 925; 425 925; 650 925; 925 925;
175 1170; 425 1170; 650 1170; 925 1170;
175 1425; 425 1425 ; 650 1425 ; 925 1425];
locations = sub2ind([width, height], Vals(:, 1), Vals(:, 2));
N = I(locations + (0:2) * width * height);
3 个评论
Guillaume
2019-4-9
N(i) = [array of 3 elements]
Is indeed going to result in an error since you're trying to put 3 numbers into just one slot.
N(i, :) = ...
would have worked (for N preallocated with 3 columns as you have done).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!