how to save values in a matrix from a loop
Show older comments
Hello, im programming RLE on matlab and i'm still having one issue only and it is to save my values into a matrix instead of a vector so that when i decode, i can go row by row
this is my code
clear all;
x=[2 2 2 3 3 5; 6 6 5 5 5 7]
f=size(x);
c=1;
y=[];
for i=1:f(1)
for j=1:f(2)-1
if x(i,j)==x(i,j+1)
c = c + 1;
else
y=[y c x(i,j)];
c=1;
end
end
y =[y c x(i,f(2))]
end
y
My output is coming this way y = 3 2 2 3 1 5 2 6 3 5 1 7 and instead i want it something like y = 3 2 2 3 1 5
2 6 3 5 1 7
1 Comment
Voss
on 4 Mar 2022
What would you do if the number of unique values on each row of x is not the same? For example, if
x = [2 2 2 3 3 5; 6 6 5 5 5 5]
then what would y be? Maybe this?:
y = [3 2 2 3 1 5; 2 6 4 5 0 0]
Accepted Answer
More Answers (2)
clear all;
x=[2 2 2 3 3 5; 6 6 5 5 5 7]
f=size(x);
c=1;
y = {};
for i=1:f(1)
y{i} = [];
for j=1:f(2)-1
if x(i,j)==x(i,j+1)
c = c + 1;
else
y{i}=[y{i} c x(i,j)];
c=1;
end
end
y{i} =[y{i} c x(i,f(2))]
end
y
However you should not proceed to vertcat(y{:}) because you have no reason ahead of time to believe that the encodings will be the same length for each row.
A completely different approach:
x = [2 2 2 3 3 5; 6 6 5 5 5 7];
nRow = size(x, 2);
y = cell(1, nRow); % Pre-allocate: avoid iterative growing of arrays
for k = 1:nRow
[b, n] = RunLengthEnc(x(k, :)); % Get elements and count them
y{k} = reshape([n; b], 1, []); % Store a row vector
end
% Determine run length parameters without a loop:
function [b, n] = RunLengthEnc(x)
d = [true, diff(x) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
n = diff(find([d, true])); % Number of repetitions
end
Categories
Find more on Numerical Integration and Differentiation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!