same exact results, but without any for loops
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi, I need a help. I need the same exact results, but without any for loops. It would be a great help, if you at least give me a hint. Thanks in advance.
The code is here:
clc; clear all; close all; echo off;
key = 'matlab';
text = 'AHOJJAJSEMTVUJSUPERPOMOCNIK';
keyNums = double(key);
keySorted = zeros(1, length(key));
[c cisla] = sort(keyNums);
for i = 1:length(c)
for j = 1:length(c)
if c(i) == keyNums(j) && keySorted(j) == 0
keySorted(j) = i;
break;
end
end
end
k = 1;
l = 1;
for i = 1:size(text, 2)
M(k, l) = text(i);
l = l + 1;
if mod(i, 6) == 0
k = k+1;
l = 1;
end
end
for i=1:length(keySorted)
for j = 1:length(keySorted)
if i == keySorted(j)
cipher{i} = M(:,j)';
end
end
end
strjoin(cipher, '')
0 Kommentare
Antworten (1)
Deepak
am 27 Aug. 2024
Hi @Tvoje Máma, from my understanding, you have a code that calculates “cipher” array as result. Now, you want to achieve the same result without using “for loops” in the code.
To do this, we can use Array manipulation and logical indexing functions in MATLAB that allows us to efficiently access, modify, and analyse the data within arrays.
To ensure the text fits perfectly into the matrix, we will utilize the “repmat()” function to create a string of space for padding. Next, we will use “reshape()” function to transform the padded text into matrix format. Finally, we will use “strttrim()” function to remove any leading or trailing spaces from the string. The “arrayfun()” helps to apply any function to each element of the array.
Attaching the documentation of methods used for reference:
Below is the complete MATLAB code that addresses this task:
clc; clear all; close all; echo off;
key = 'matlab';
text = 'AHOJJAJSEMTVUJSUPERPOMOCNIK';
keyNums = double(key);
[~, cisla] = sort(keyNums);
numRows = ceil(length(text) / length(key));
% Pad the text with spaces if necessary
paddedText = [text, repmat(' ', 1, numRows * length(key) - length(text))];
% Reshape the padded text into a matrix
M = reshape(paddedText, length(key), numRows)';
M_sorted = M(:, cisla);
% Convert sorted matrix to cell array of strings, also removing leading or trailing spaces with strtrim() method
cipher = arrayfun(@(col) strtrim(M_sorted(:, col)'), 1:size(M_sorted, 2), 'UniformOutput', false);
result = strjoin(strtrim(cipher), ' ');
disp(result);
I hope this helps.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!